Пример #1
0
def getModel (n_input, n_output):
    model = Sequential()
    model.add(LSTM(32, input_shape=(int(n_input / conf['n_timesteps']), conf['n_timesteps'])))
    model.add(Dense(1))

    return model
    
def get_model_1(x,y,Vocab_size,maxlen):
    model = Sequential()
    model.add(Embedding(Vocab_size, 30)) #input_length=maxlen))
    model.add(LSTM(60, return_sequences=True))
    model.add(Dense(60, activation='relu'))
    model.add(Dense(Vocab_size))
    model.add(Activation("softmax"))
    print(model.summary())
    optimizer = RMSprop(lr=0.01)
    model.compile(loss="sparse_categorical_crossentropy", optimizer='adam')
    return model
Пример #3
0
def _get_simple_sequential_model(compile_metrics):
  model = Sequential()
  model.add(
      layers.Dense(
          3, activation='relu', input_dim=4, kernel_initializer='ones'))
  model.add(layers.Dense(1, activation='sigmoid', kernel_initializer='ones'))
  model.compile(
      loss='mae',
      metrics=compile_metrics,
      optimizer=RMSPropOptimizer(learning_rate=0.001))
  return model
Пример #4
0
def getModel (n_input, n_output):
    model = Sequential()
    model.add(Dense(round(n_input * 2), activation='relu' , input_dim=n_input))
    model.add(Dense(n_input, activation="relu"))
    model.add(Dense(units=n_output, activation='softmax'))  

    return model
Пример #5
0
def getModel (n_input, n_output):
    
    model = Sequential()
    #model.add(LSTM(round(n_input), input_shape=(conf['n_timesteps'], int(n_input / conf['n_timesteps']))))
    model.add(Dense(round(n_input), activation='relu' , input_dim=n_input))
    model.add(Dense(round(n_input/2), activation='relu'))
    model.add(Dense(units=n_output, activation='tanh'))

    return model
Пример #6
0
def getModel (n_input, n_output):
    model = Sequential()
    
    # model.add(Dense(round(n_input * 2), activation='relu' , input_dim=n_input))
    # model.add(Dropout(0.5))
    # model.add(CustomDropout(conf['dropout_rate'], conf['perma_drop']))
    # model.add(Dense(round(n_input), activation='relu'))
    # model.add(Dense(round(n_input / 2), activation='relu'))
    # model.add(CustomDropout(conf['dropout_rate'], conf['perma_drop']))
    # model.add(Dense(round(n_input / 3), activation='relu'))
    # model.add(Dense(units=n_output, activation='sigmoid'))  
    
    # model = Sequential()
    # model.add(Dense(round(n_input), activation='relu', input_dim=n_input)) 
    # model.add(Dropout(conf['dropout_rate']))
    # model.add(Dense(units=round(n_input ), activation='relu'))    
    # model.add(Dense(units=round(n_input / 2 ), activation='relu'))         
    # model.add(Dense(units=n_output, activation='sigmoid'))  
    
    asdf = random.seed()
    
    # model.add(Dense(round(n_input), activation='relu' ,kernel_initializer=glorot_uniform(seed=asdf), input_dim=n_input))
    # model.add(Dropout(0.5))
    # model.add(Dense(round(n_input / 2), activation='relu',kernel_initializer=glorot_uniform(seed=asdf)))
    # model.add(Dropout(0.5))
    # model.add(Dense(round(n_input / 3), activation='relu', kernel_initializer=glorot_uniform(seed=asdf)))
    # model.add(Dense(units=n_output, activation='sigmoid', kernel_initializer=glorot_uniform(seed=asdf)))
    
    #model.add(Dense(round(n_input * 2), activation='relu' , input_dim=n_input,kernel_initializer=glorot_uniform(seed=asdf)))
    model.add(LSTM(32, input_shape=(int(n_input / conf['n_timesteps']), conf['n_timesteps'])))
    model.add(Dropout(0.25))
    model.add(Dense(round(n_input), activation='relu',kernel_initializer=glorot_uniform(seed=asdf)))
    model.add(Dense(round(n_input / 2), activation='relu',kernel_initializer=glorot_uniform(seed=asdf)))
    model.add(Dense(units=n_output, activation='sigmoid',kernel_initializer=glorot_uniform(seed=asdf)))  

    return model
Пример #7
0
def getModel (n_input, n_output):
    model = Sequential()
    model.add(Dense(round(n_input * 2), activation='relu' , input_dim=n_input))
    model.add(Dropout(0.5))
    model.add(CustomDropout(conf['dropout_rate'], conf['perma_drop']))
    model.add(Dense(round(n_input), activation='relu'))
    model.add(Dense(round(n_input / 2), activation='relu'))
    model.add(CustomDropout(conf['dropout_rate'], conf['perma_drop']))
    model.add(Dense(round(n_input / 3), activation='relu'))
    model.add(Dense(units=n_output, activation='tanh'))  

    return model
def keras_model_fn(hyperparameters):
    """keras_model_fn receives hyperparameters from the training job and returns a compiled keras model.
    The model will be transformed into a TensorFlow Estimator before training and it will be saved in a
    TensorFlow Serving SavedModel at the end of training.
    Args:
        hyperparameters: The hyperparameters passed to the SageMaker TrainingJob that runs your TensorFlow
                         training script.
    Returns: A compiled Keras model
    """
    model = Sequential()

    # TensorFlow Serving default prediction input tensor name is PREDICT_INPUTS.
    # We must conform to this naming scheme.
    model.add(InputLayer(input_shape=(HEIGHT, WIDTH, DEPTH), name=PREDICT_INPUTS))
    model.add(Conv2D(32, (3, 3), padding='same'))
    model.add(Activation('relu'))
    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))

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

    model.add(Flatten())
    model.add(Dense(512))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(NUM_CLASSES))
    model.add(Activation('softmax'))

    _model = tf.keras.Model(inputs=model.input, outputs=model.output)

    opt = RMSprop(lr=hyperparameters['learning_rate'], decay=hyperparameters['decay'])

    _model.compile(loss='categorical_crossentropy',
                   optimizer=opt,
                   metrics=['accuracy'])

    return _model
Пример #9
0
# split into input and output variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
print(X)
print(Y)

# split the data into training (67%) and testing (33%)
(X_train, X_test, Y_train, Y_test) = train_test_split(X,
                                                      Y,
                                                      test_size=0.33,
                                                      random_state=seed)

# create the model
model = Sequential()
model.add(Dense(8, input_dim=8, activation='relu'))
model.add(Dense(6, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

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

# fit the model
model.fit(X_train,
          Y_train,
          validation_data=(X_test, Y_test),
          nb_epoch=200,
          batch_size=5,
          verbose=0)
Пример #10
0
print('y_test.shape: ', y_test.shape)  # (10000, )

# Preprocessing - exchange the scale of data
x_train = x_train.reshape(60000, 784)
x_train = x_train / 255
x_test = x_test.reshape(10000, 784)
x_test = x_test / 255

# Preprocessing - change class label to 1-hot vector
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

# Create the neural network
# Input layer -> Hidden layer
model = Sequential()
model.add(Dense(units=64, input_shape=(784, ), activation='relu'))

# Hidden layer -> Output layer
model.add(Dense(units=10, activation='softmax'))

# Learn the model
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
tsb = TensorBoard(log_dir='./logs')
history_adam = model.fit(x_train,
                         y_train,
                         batch_size=32,
                         epochs=20,
                         validation_split=0.2,
                         callbacks=[tsb])
Пример #11
0
def VGG16(save_dir):
    VGG16 = Sequential()
    VGG16.add(
        Conv2D(64, (3, 3),
               strides=(1, 1),
               input_shape=(224, 224, 3),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(64, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(MaxPooling2D(pool_size=(2, 2)))
    VGG16.add(
        Conv2D(128, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(128, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(MaxPooling2D(pool_size=(2, 2)))
    VGG16.add(
        Conv2D(256, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(256, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(256, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(MaxPooling2D(pool_size=(2, 2)))
    VGG16.add(
        Conv2D(512, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(512, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(512, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(MaxPooling2D(pool_size=(2, 2)))
    VGG16.add(
        Conv2D(512, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(512, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(
        Conv2D(512, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    VGG16.add(MaxPooling2D(pool_size=(2, 2)))
    VGG16.add(Flatten())
    VGG16.add(Dense(4096, activation='relu'))
    VGG16.add(Dropout(0.5))
    VGG16.add(Dense(4096, activation='relu'))
    VGG16.add(Dropout(0.5))
    VGG16.add(Dense(1000, activation='softmax'))
    VGG16.compile(loss='categorical_crossentropy',
                  optimizer='sgd',
                  metrics=['accuracy'])
    VGG16.summary()
    save_dir += 'VGG16.h5'
    return VGG16
Пример #12
0
def discriminator():
    model = Sequential()
    model.add(
        Conv3D(64, (3, 3, 3),
               activation='relu',
               padding="same",
               input_shape=(20, 5, 97, 1)))
    model.add(MaxPooling3D((2, 2, 2)))
    model.add(Conv3D(128, (3, 3, 3), activation='relu', padding="same"))
    model.add(MaxPooling3D((2, 2, 2)))
    model.add(Conv3D(512, (3, 3, 3), activation='relu', padding="same"))
    model.add(Dropout(0.2))
    model.add(Conv3D(1024, (3, 3, 3), activation='relu', padding="same"))
    model.add(LeakyReLU(0.2))
    model.add(Flatten())
    model.add(Dense(1, activation='sigmoid'))
    model.compile(loss='binary_crossentropy',
                  optimizer=RMSProp(),
                  metrics=['acc'])
    return model
Пример #13
0
RNN无法处理如此广泛的数值。 嵌入层被训练为RNN的一部分,并将学习将具有
相似语义含义的单词映射到相似的嵌入向量,如下面将进一步示出的那样。

首先我们为每个整数标记定义嵌入向量的大小。 在这种情况下,我们将其设置为8,
以便每个整数标记都将转换为长度为8的矢量。嵌入矢量的值通常大致落在-1.0和1.0之间,尽管它们可能会略微超过这些值。

嵌入向量的大小通常在100-300之间选择,但对于情感分析来说,它似乎可以很好地工作。
'''
embedding_size = 8
'''
嵌入层还需要知道词汇表(num_words)中的单词数量和填充的标记序列(max_tokens)的长度。 
我们也给这个图层一个名字,因为我们需要在下面进一步检索它的权重。
'''
model.add(
    Embedding(input_dim=num_words,
              output_dim=embedding_size,
              input_length=max_tokens,
              name='layer_embedding'))  # [n,544,8]

model.add(GRU(units=16, return_sequences=True))  # [n,n,16]

model.add(GRU(units=8, return_sequences=True))  # [n,n,8]

model.add(GRU(units=4))  # [n,4]

model.add(Dense(1, activation='sigmoid'))  # [n,1]

optimizer = Adam(lr=1e-3)

model.compile(loss='binary_crossentropy',
              optimizer=optimizer,
Пример #14
0
class RNNGRU(object):
    """Process data for ingestion."""

    def __init__(
            self, data, periods=288, batch_size=64, sequence_length=20,
            warmup_steps=50, epochs=20, display=False):
        """Instantiate the class.

        Args:
            data: Dict of values keyed by timestamp
            periods: Number of timestamp data points per vector
            batch_size: Size of batch
            sequence_length: Length of vectors for for each target
            warmup_steps:

        Returns:
            None

        """
        # Initialize key variables
        self.periods = periods
        self.target_names = ['value']
        self.warmup_steps = warmup_steps
        self.epochs = epochs
        self.batch_size = batch_size
        self.display = display

        ###################################
        # TensorFlow wizardry
        config = tf.ConfigProto()

        # Don't pre-allocate memory; allocate as-needed
        config.gpu_options.allow_growth = True

        # Only allow a total of half the GPU memory to be allocated
        config.gpu_options.per_process_gpu_memory_fraction = 0.95

        # Crash with DeadlineExceeded instead of hanging forever when your
        # queues get full/empty
        config.operation_timeout_in_ms = 60000

        # Create a session with the above options specified.
        backend.tensorflow_backend.set_session(tf.Session(config=config))
        ###################################

        # Get data
        (x_data, y_data) = convert_data(data, periods, self.target_names)

        print('\n> Numpy Data Type: {}'.format(type(x_data)))
        print("> Numpy Data Shape: {}".format(x_data.shape))
        print("> Numpy Data Row[0]: {}".format(x_data[0]))
        print('> Numpy Targets Type: {}'.format(type(y_data)))
        print("> Numpy Targets Shape: {}".format(y_data.shape))

        '''
        This is the number of observations (aka. data-points or samples) in
        the data-set:
        '''

        num_data = len(x_data)

        '''
        This is the fraction of the data-set that will be used for the
        training-set:
        '''

        train_split = 0.9

        '''
        This is the number of observations in the training-set:
        '''

        self.num_train = int(train_split * num_data)

        '''
        This is the number of observations in the test-set:
        '''

        num_test = num_data - self.num_train

        print('> Number of Samples: {}'.format(num_data))
        print("> Number of Training Samples: {}".format(self.num_train))
        print("> Number of Test Samples: {}".format(num_test))

        # Create test and training data
        x_train = x_data[0:self.num_train]
        x_test = x_data[self.num_train:]
        self.y_train = y_data[0:self.num_train]
        self.y_test = y_data[self.num_train:]
        self.num_x_signals = x_data.shape[1]
        self.num_y_signals = y_data.shape[1]

        print("> Training Minimum Value:", np.min(x_train))
        print("> Training Maximum Value:", np.max(x_train))

        '''
        steps_per_epoch is the number of batch iterations before a training
        epoch is considered finished.
        '''

        self.steps_per_epoch = int(self.num_train / batch_size) + 1
        print("> Epochs:", epochs)
        print("> Batch Size:", batch_size)
        print("> Steps:", self.steps_per_epoch)

        '''
        Calculate the estimated memory footprint.
        '''

        print("> Data size: {:.2f} Bytes".format(x_data.nbytes))

        '''
        if memory_footprint > 7:
            print('\n\n{}\n\n'.format(
                '> Estimated GPU memory usage too large. Use new parameters '
                'to reduce the footprint.'))
            sys.exit(0)
        '''

        '''
        The neural network works best on values roughly between -1 and 1, so we
        need to scale the data before it is being input to the neural network.
        We can use scikit-learn for this.

        We first create a scaler-object for the input-signals.

        Then we detect the range of values from the training-data and scale
        the training-data.
        '''

        x_scaler = MinMaxScaler()
        self.x_train_scaled = x_scaler.fit_transform(x_train)

        print('> Scaled Training Minimum Value: {}'.format(
            np.min(self.x_train_scaled)))
        print('> Scaled Training Maximum Value: {}'.format(
            np.max(self.x_train_scaled)))

        self.x_test_scaled = x_scaler.transform(x_test)

        '''
        The target-data comes from the same data-set as the input-signals,
        because it is the weather-data for one of the cities that is merely
        time-shifted. But the target-data could be from a different source with
        different value-ranges, so we create a separate scaler-object for the
        target-data.
        '''

        self.y_scaler = MinMaxScaler()
        self.y_train_scaled = self.y_scaler.fit_transform(self.y_train)
        y_test_scaled = self.y_scaler.transform(self.y_test)

        # Data Generator

        '''
        The data-set has now been prepared as 2-dimensional numpy arrays. The
        training-data has almost 300k observations, consisting of 20
        input-signals and 3 output-signals.

        These are the array-shapes of the input and output data:
        '''

        print('> Scaled Training Data Shape: {}'.format(
            self.x_train_scaled.shape))
        print('> Scaled Training Targets Shape: {}'.format(
            self.y_train_scaled.shape))

        # We then create the batch-generator.

        generator = self.batch_generator(batch_size, sequence_length)

        # Validation Set

        '''
        The neural network trains quickly so we can easily run many training
        epochs. But then there is a risk of overfitting the model to the
        training-set so it does not generalize well to unseen data. We will
        therefore monitor the model's performance on the test-set after each
        epoch and only save the model's weights if the performance is improved
        on the test-set.

        The batch-generator randomly selects a batch of short sequences from
        the training-data and uses that during training. But for the
        validation-data we will instead run through the entire sequence from
        the test-set and measure the prediction accuracy on that entire
        sequence.
        '''

        validation_data = (np.expand_dims(self.x_test_scaled, axis=0),
                           np.expand_dims(y_test_scaled, axis=0))

        # Create the Recurrent Neural Network

        self.model = Sequential()

        '''
        We can now add a Gated Recurrent Unit (GRU) to the network. This will
        have 512 outputs for each time-step in the sequence.

        Note that because this is the first layer in the model, Keras needs to
        know the shape of its input, which is a batch of sequences of arbitrary
        length (indicated by None), where each observation has a number of
        input-signals (num_x_signals).
        '''

        self.model.add(GRU(
            units=512,
            return_sequences=True,
            input_shape=(None, self.num_x_signals,)))

        '''
        The GRU outputs a batch of sequences of 512 values. We want to predict
        3 output-signals, so we add a fully-connected (or dense) layer which
        maps 512 values down to only 3 values.

        The output-signals in the data-set have been limited to be between 0
        and 1 using a scaler-object. So we also limit the output of the neural
        network using the Sigmoid activation function, which squashes the
        output to be between 0 and 1.'''

        self.model.add(Dense(self.num_y_signals, activation='sigmoid'))

        '''
        A problem with using the Sigmoid activation function, is that we can
        now only output values in the same range as the training-data.

        For example, if the training-data only has temperatures between -20
        and +30 degrees, then the scaler-object will map -20 to 0 and +30 to 1.
        So if we limit the output of the neural network to be between 0 and 1
        using the Sigmoid function, this can only be mapped back to temperature
        values between -20 and +30.

        We can use a linear activation function on the output instead. This
        allows for the output to take on arbitrary values. It might work with
        the standard initialization for a simple network architecture, but for
        more complicated network architectures e.g. with more layers, it might
        be necessary to initialize the weights with smaller values to avoid
        NaN values during training. You may need to experiment with this to
        get it working.
        '''

        if False:
            # Maybe use lower init-ranges.
            # init = RandomUniform(minval=-0.05, maxval=0.05)
            init = RandomUniform(minval=-0.05, maxval=0.05)

            self.model.add(Dense(
                self.num_y_signals,
                activation='linear',
                kernel_initializer=init))

        # Compile Model

        '''
        This is the optimizer and the beginning learning-rate that we will use.
        We then compile the Keras model so it is ready for training.
        '''
        optimizer = RMSprop(lr=1e-3)
        self.model.compile(loss=self.loss_mse_warmup, optimizer=optimizer)

        '''
        This is a very small model with only two layers. The output shape of
        (None, None, 3) means that the model will output a batch with an
        arbitrary number of sequences, each of which has an arbitrary number of
        observations, and each observation has 3 signals. This corresponds to
        the 3 target signals we want to predict.
        '''
        print('> Model Summary:\n')
        print(self.model.summary())

        # Callback Functions

        '''
        During training we want to save checkpoints and log the progress to
        TensorBoard so we create the appropriate callbacks for Keras.

        This is the callback for writing checkpoints during training.
        '''

        path_checkpoint = '/tmp/23_checkpoint.keras'
        callback_checkpoint = ModelCheckpoint(filepath=path_checkpoint,
                                              monitor='val_loss',
                                              verbose=1,
                                              save_weights_only=True,
                                              save_best_only=True)

        '''
        This is the callback for stopping the optimization when performance
        worsens on the validation-set.
        '''

        callback_early_stopping = EarlyStopping(monitor='val_loss',
                                                patience=5, verbose=1)

        '''
        This is the callback for writing the TensorBoard log during training.
        '''

        callback_tensorboard = TensorBoard(log_dir='/tmp/23_logs/',
                                           histogram_freq=0,
                                           write_graph=False)

        '''
        This callback reduces the learning-rate for the optimizer if the
        validation-loss has not improved since the last epoch
        (as indicated by patience=0). The learning-rate will be reduced by
        multiplying it with the given factor. We set a start learning-rate of
        1e-3 above, so multiplying it by 0.1 gives a learning-rate of 1e-4.
        We don't want the learning-rate to go any lower than this.
        '''

        callback_reduce_lr = ReduceLROnPlateau(monitor='val_loss',
                                               factor=0.1,
                                               min_lr=1e-4,
                                               patience=0,
                                               verbose=1)

        callbacks = [callback_early_stopping,
                     callback_checkpoint,
                     callback_tensorboard,
                     callback_reduce_lr]

        # Train the Recurrent Neural Network

        '''We can now train the neural network.

        Note that a single "epoch" does not correspond to a single processing
        of the training-set, because of how the batch-generator randomly
        selects sub-sequences from the training-set. Instead we have selected
        steps_per_epoch so that one "epoch" is processed in a few minutes.

        With these settings, each "epoch" took about 2.5 minutes to process on
        a GTX 1070. After 14 "epochs" the optimization was stopped because the
        validation-loss had not decreased for 5 "epochs". This optimization
        took about 35 minutes to finish.

        Also note that the loss sometimes becomes NaN (not-a-number). This is
        often resolved by restarting and running the Notebook again. But it may
        also be caused by your neural network architecture, learning-rate,
        batch-size, sequence-length, etc. in which case you may have to modify
        those settings.
        '''

        print('\n> Starting data training\n')

        try:
            self.model.fit_generator(
                generator=generator,
                epochs=self.epochs,
                steps_per_epoch=self.steps_per_epoch,
                validation_data=validation_data,
                callbacks=callbacks)
        except Exception as error:
            print('\n>{}\n'.format(error))
            traceback.print_exc()
            sys.exit(0)

        # Load Checkpoint

        '''
        Because we use early-stopping when training the model, it is possible
        that the model's performance has worsened on the test-set for several
        epochs before training was stopped. We therefore reload the last saved
        checkpoint, which should have the best performance on the test-set.
        '''

        print('> Loading model weights')

        try:
            self.model.load_weights(path_checkpoint)
        except Exception as error:
            print('\n> Error trying to load checkpoint.\n\n{}'.format(error))
            traceback.print_exc()
            sys.exit(0)

        # Performance on Test-Set

        '''
        We can now evaluate the model's performance on the test-set. This
        function expects a batch of data, but we will just use one long
        time-series for the test-set, so we just expand the
        array-dimensionality to create a batch with that one sequence.
        '''

        result = self.model.evaluate(
            x=np.expand_dims(self.x_test_scaled, axis=0),
            y=np.expand_dims(y_test_scaled, axis=0))

        print('> Loss (test-set): {}'.format(result))

        # If you have several metrics you can use this instead.
        if False:
            for res, metric in zip(result, self.model.metrics_names):
                print('{0}: {1:.3e}'.format(metric, res))

    def batch_generator(self, batch_size, sequence_length):
        """Create generator function to create random batches of training-data.

        Args:
            batch_size: Size of batch
            sequence_length: Length of sequence

        Returns:
            (x_batch, y_batch)

        """
        # Infinite loop.
        while True:
            # Allocate a new array for the batch of input-signals.
            x_shape = (batch_size, sequence_length, self.num_x_signals)
            x_batch = np.zeros(shape=x_shape, dtype=np.float16)

            # Allocate a new array for the batch of output-signals.
            y_shape = (batch_size, sequence_length, self.num_y_signals)
            y_batch = np.zeros(shape=y_shape, dtype=np.float16)

            # Fill the batch with random sequences of data.
            for i in range(batch_size):
                # Get a random start-index.
                # This points somewhere into the training-data.
                idx = np.random.randint(self.num_train - sequence_length)

                # Copy the sequences of data starting at this index.
                x_batch[i] = self.x_train_scaled[idx:idx+sequence_length]
                y_batch[i] = self.y_train_scaled[idx:idx+sequence_length]

            yield (x_batch, y_batch)

    def loss_mse_warmup(self, y_true, y_pred):
        """Calculate the Mean Squared Errror.

        Calculate the Mean Squared Error between y_true and y_pred,
        but ignore the beginning "warmup" part of the sequences.

        We will use Mean Squared Error (MSE) as the loss-function that will be
        minimized. This measures how closely the model's output matches the
        true output signals.

        However, at the beginning of a sequence, the model has only seen
        input-signals for a few time-steps, so its generated output may be very
        inaccurate. Using the loss-value for the early time-steps may cause the
        model to distort its later output. We therefore give the model a
        "warmup-period" of 50 time-steps where we don't use its accuracy in the
        loss-function, in hope of improving the accuracy for later time-steps

        Args:
            y_true: Desired output.
            y_pred: Model's output.

        Returns:
            loss_mean: Mean Squared Error

        """
        warmup_steps = self.warmup_steps

        # The shape of both input tensors are:
        # [batch_size, sequence_length, num_y_signals].

        # Ignore the "warmup" parts of the sequences
        # by taking slices of the tensors.
        y_true_slice = y_true[:, warmup_steps:, :]
        y_pred_slice = y_pred[:, warmup_steps:, :]

        # These sliced tensors both have this shape:
        # [batch_size, sequence_length - warmup_steps, num_y_signals]

        # Calculate the MSE loss for each value in these tensors.
        # This outputs a 3-rank tensor of the same shape.
        loss = tf.losses.mean_squared_error(labels=y_true_slice,
                                            predictions=y_pred_slice)

        # Keras may reduce this across the first axis (the batch)
        # but the semantics are unclear, so to be sure we use
        # the loss across the entire tensor, we reduce it to a
        # single scalar with the mean function.
        loss_mean = tf.reduce_mean(loss)

        return loss_mean

    def plot_comparison(self, start_idx, length=100, train=True):
        """Plot the predicted and true output-signals.

        Args:
            start_idx: Start-index for the time-series.
            length: Sequence-length to process and plot.
            train: Boolean whether to use training- or test-set.

        Returns:
            None

        """
        if train:
            # Use training-data.
            x_values = self.x_train_scaled
            y_true = self.y_train
            shim = 'Train'
        else:
            # Use test-data.
            x_values = self.x_test_scaled
            y_true = self.y_test
            shim = 'Test'

        # End-index for the sequences.
        end_idx = start_idx + length

        # Select the sequences from the given start-index and
        # of the given length.
        x_values = x_values[start_idx:end_idx]
        y_true = y_true[start_idx:end_idx]

        # Input-signals for the model.
        x_values = np.expand_dims(x_values, axis=0)

        # Use the model to predict the output-signals.
        y_pred = self.model.predict(x_values)

        # The output of the model is between 0 and 1.
        # Do an inverse map to get it back to the scale
        # of the original data-set.
        y_pred_rescaled = self.y_scaler.inverse_transform(y_pred[0])

        # For each output-signal.
        for signal in range(len(self.target_names)):
            # Create a filename
            filename = (
                '/tmp/batch_{}_epochs_{}_training_{}_{}_{}_{}.png').format(
                    self.batch_size, self.epochs, self.num_train, signal,
                    int(time.time()), shim)

            # Get the output-signal predicted by the model.
            signal_pred = y_pred_rescaled[:, signal]

            # Get the true output-signal from the data-set.
            signal_true = y_true[:, signal]

            # Make the plotting-canvas bigger.
            plt.figure(figsize=(15, 5))

            # Plot and compare the two signals.
            plt.plot(signal_true, label='true')
            plt.plot(signal_pred, label='pred')

            # Plot grey box for warmup-period.
            _ = plt.axvspan(
                0, self.warmup_steps, facecolor='black', alpha=0.15)

            # Plot labels etc.
            plt.ylabel(self.target_names[signal])
            plt.legend()

            # Show and save the image
            if self.display is True:
                plt.savefig(filename, bbox_inches='tight')
                plt.show()
            else:
                plt.savefig(filename, bbox_inches='tight')
            print('> Saving file: {}'.format(filename))
Пример #15
0
    def createModel(self, inputs, outputs, hiddenLayers, activationType,
                    learningRate):
        model = Sequential()
        if len(hiddenLayers) == 0:
            model.add(
                Dense(self.output_size,
                      input_shape=(self.input_size, ),
                      init='lecun_uniform'))
            model.add(Activation('linear'))
        else:
            model.add(
                Dense(hiddenLayers[0],
                      input_shape=(self.input_size, ),
                      kernel_initializer='lecun_uniform'))
            if activationType == 'LeakyReLU':
                model.add(LeakyReLU(alpha=0.01))
            else:
                model.add(Activation(activationType))

            for index in range(1, len(hiddenLayers)):
                layerSize = hiddenLayers[index]
                model.add(Dense(layerSize, kernel_initializer='lecun_uniform'))
                if activationType == 'LeakyReLU':
                    model.add(LeakyReLU(alpha=0.01))
                else:
                    model.add(Activation(activationType))
            model.add(
                Dense(self.output_size, kernel_initializer='lecun_uniform'))
            model.add(Activation('linear'))
        optimizer = optimizers.RMSprop(lr=learningRate, rho=0.9, epsilon=1e-6)
        model.compile(loss="mse", optimizer=optimizer)
        model.summary()
        return model
Пример #16
0
    def createRegularizedModel(
            self,
            inputs,
            outputs,
            hiddenLayers,  # List of nodes at each hidden layer
            activationType,
            learningRate):
        bias = True
        dropout = 0
        regularizationFactor = 0.01
        model = Sequential()
        if len(hiddenLayers) == 0:
            model.add(
                Dense(self.output_size,
                      input_shape=(self.input_size, ),
                      init='lecun_uniform',
                      bias=bias))
            model.add(Activation("linear"))
        else:
            if regularizationFactor > 0:
                model.add(
                    Dense(hiddenLayers[0],
                          input_shape=(self.input_size, ),
                          init='lecun_uniform',
                          W_regularizer=l2(regularizationFactor),
                          bias=bias))
            else:
                model.add(
                    Dense(hiddenLayers[0],
                          input_shape=(self.input_size, ),
                          init='lecun_uniform',
                          bias=bias))
            if activationType == 'LeakyReLU':
                model.add(LeakyReLU(alpha=0.01))
            else:
                model.add(Activation(activationType))

            for index in range(1, len(hiddenLayers)):
                layerSize = hiddenSize[index]
                if regularizationFactor > 0.0:
                    model.add(
                        Dense(hiddenLayers[index],
                              init='lecun_uniform',
                              W_regularizer=l2(regularizationFactor),
                              bias=bias))
                else:
                    model.add(
                        Dense(hiddenLayers[index],
                              init='lecun_uniform',
                              bias=bias))
                if activationType == "LeakyReLU":
                    model.add(LeakyReLU(alpha=0.01))
                else:
                    model.add(Activation(activationType))
                if dropout > 0:
                    model.add(Dropout(dropout))
            model.add(Dense(self.output_size, init='lecun_uniform', bias=bias))
            model.add(Activation("linear"))
        optimizer = optimizers.RMSprop(lr=learningRate, rho=0.9, epsilon=1e-6)
        model.compile(loss="mse", optimizer=optimizer)
        model.summary()
        return model
Пример #17
0
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist", one_hot=True)

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Activation

model = Sequential()
model.add(Dense(10, input_shape=(784, )))
model.add(Activation('softmax'))

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

model.fit(mnist.train.images, mnist.train.labels, epochs=20, batch_size=128)

scores = model.evaluate(mnist.test.images, mnist.test.labels, verbose=1)
print('Test accuracy:', scores[1])
Пример #18
0
import numpy as np
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense

filename = 'logicalTest02.csv'
data = np.loadtxt(filename, delimiter=',')

table_col = data.shape[1]
y_column = 1
x_column = table_col - y_column

x_train = data[:, 0:x_column]
y_train = data[:, x_column:]

model = Sequential()
model.add(Dense(input_dim=x_column, units=y_column, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(x_train, y_train, epochs=5000, batch_size=100, verbose=0)
x_test = [[2, 1], [6, 5], [11, 6]]


# 0 : 강아지, 1 : 고양이
def getCategory(mydata):
    mylist = ['강아지', '고양이']
    print(f'예측 : {mydata}, {mylist[mydata[0]]}')


for i in x_test:
    # pred = np.argmax(model.predict(np.array([i])), axis=-1)
    pred = model.predict_classes(np.array([i]))
    getCategory(pred.flatten())  # flatten() : 다차원을 1차원으로 만들어 주는 함수
Пример #19
0
y_test = sc_y.transform(y_test)

dump(sc_x, open(dataset + '/scalers/scaler_x_MO_' + dataset + '.pkl', 'wb'))
dump(sc_y, open(dataset + '/scalers/scaler_y_MO_' + dataset + '.pkl', 'wb'))

print('Training Features Shape:', x_train.shape)
print('Training Labels Shape:', y_train.shape)
print('Testing Features Shape:', x_test.shape)
print('Testing Labels Shape:', y_test.shape)

print("[INFO] Model build ...")
model = Sequential()

model.add(
    Dense(126,
          input_dim=in_dim,
          kernel_initializer='normal',
          activation='relu'))
#model.add(layers.Dropout(0.5))
#model.add(Dense(60, kernel_initializer='normal', activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.001)))
#model.add(Dense(126, activation='linear'))
# https://www.datatechnotes.com/2019/12/multi-output-regression-example-with.html
model.add(Dense(out_dim, activation='linear'))

#opt = keras.optimizers.SGD(lr=0.01, momentum=0.9, decay=0.01)
opt = keras.optimizers.Adam(learning_rate=0.01)

model.summary()

keras2ascii(model)
Пример #20
0
def lenet(network_input: NetworkInput) -> Model:
    model = Sequential()

    model.add(layers.Lambda(lambda x: norm(x, network_input.mean, network_input.std), input_shape=network_input.input_shape, output_shape=network_input.input_shape))
    model.add(layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))
    
    model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    model.add(layers.Dropout(0.2))
    
    model.add(layers.Flatten())
    model.add(layers.Dense(128, activation='relu'))
    model.add(layers.Dropout(0.2))
    
    model.add(layers.Dense(network_input.number_of_classes, activation='softmax'))

    return model
Пример #21
0
Y_validation = Y_validation.values

# Make sure everything is ok
assert X_train['left'].shape == X_train['right'].shape
assert len(X_train['left']) == len(Y_train)

batch_size = 512
n_epoch = 50
n_hidden = 128
#the increase of n_hidden node can improve the performance because the w2v is 300 dim. dont compress too much info.

# Define the shared model
x = Sequential()
x.add(
    Embedding(len(embeddings),
              embedding_dim,
              weights=[embeddings],
              input_shape=(max_seq_length, ),
              trainable=False))

# LSTM
x.add(LSTM(n_hidden))

shared_model = x

# The visible layer
left_input = Input(shape=(max_seq_length, ), dtype='int32')
right_input = Input(shape=(max_seq_length, ), dtype='int32')

# Pack it all up into a Manhattan Distance model
malstm_distance = ManDist()(
    [shared_model(left_input),
Пример #22
0
def compile(dim):
    '''
    Compile the keras neural network model

    Needs to take in **kwargs params later
    '''
    model = Sequential()

    # dim = len(X.columns)

    model.add(
        Dense(dim,
              input_dim=dim,
              kernel_initializer='orthogonal',
              activation='relu'))
    model.add(BatchNormalization())
    model.add(Dense(math.floor(dim / 2), activation='relu'))
    model.add(BatchNormalization())
    model.add(Dropout(0.3, seed=7))
    model.add(BatchNormalization())
    model.add(Dense(1, activation='linear'))

    # Fit model, evaluate model, and generate predictions
    # NOTE - Loss improves for about ~40 epochs. Not sure how to interpret mean_squared_logarithmic_error
    model.compile(loss='mean_squared_logarithmic_error', optimizer='adam')

    return model
Пример #23
0
x_test = x_test.astype('float32')
x_train /= 255  # normalise
x_test /= 255

from tensorflow.python.keras.utils import to_categorical
# One-hot encode the labels
num_classes = 10
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
"""Define Model"""

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Conv2D, Activation, MaxPooling2D, Dropout, Flatten, Dense

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', input_shape=x_train.shape[1:]))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
model.add(Dropout(0.25))

model.add(Flatten())
Пример #24
0
x = np.load('./lego_class_data.npy')
y = np.load('./lego_class_labels.npy')

# 5. Preprocess input data
X_test = np.expand_dims((x[:,:,:1000].astype('float32') / 255), axis=3).transpose((2,0,1,3))
X_train = np.expand_dims((x[:,:,1000:].astype('float32') / 255), axis=3).transpose((2,0,1,3))
Y_test = y[:1000,0]
Y_train = y[1000:,0]    # First column marks if data exists
 
# 6. Preprocess class labels
Y_train = np_utils.to_categorical(Y_train.astype('uint8'),2)
Y_test = np_utils.to_categorical(Y_test.astype('uint8'),2)
 
# 7. Define model architecture
model = Sequential()
model.add(ZeroPadding2D((1,1),input_shape=(100,100,1)))
model.add(Convolution2D(64, 2, 2, activation='relu', padding = 'same'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(64, 2, 2, activation='relu', padding = 'same'))
model.add(MaxPooling2D((2,2)))

model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(128, 2, 2, activation='relu', padding = 'same'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(128, 2, 2, activation='relu', padding = 'same'))
model.add(MaxPooling2D((2,2)))

model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(256, 2, 2, activation='relu', padding = 'same'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(256, 2, 2, activation='relu', padding = 'same'))
Пример #25
0
#from keras_applications.resnet import ResNet152
from tensorflow.python.keras.applications import ResNet50
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D

from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator

#number of files in car_data/train
num_classes = 196

#weights taken from https://gist.github.com/flyyufelix/7e2eafb149f72f4d38dd661882c554a6
#resnet_weights_path = 'resnet152_weights_tf.h5'

my_model = Sequential()
my_model.add(ResNet50(include_top=False, pooling='avg', weights='imagenet'))
my_model.add(Dense(num_classes, activation='softmax'))

#code for not training first layer (aka the resnet model)
my_model.layers[0].trainable = False

my_model.compile(optimizer='sgd',
                 loss='categorical_crossentropy',
                 metrics=['accuracy'])

image_size = 224
data_generator = ImageDataGenerator(preprocessing_function=preprocess_input)

train_generator = data_generator.flow_from_directory('train',
                                                     target_size=(image_size,
                                                                  image_size),
Пример #26
0
def ZFNet(save_dir):
    ZFNet = Sequential()
    ZFNet.add(
        Conv2D(96, (7, 7),
               strides=(2, 2),
               input_shape=(224, 224, 3),
               padding='valid',
               activation='relu',
               kernel_initializer='uniform'))
    ZFNet.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
    ZFNet.add(
        Conv2D(256, (5, 5),
               strides=(2, 2),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    ZFNet.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
    ZFNet.add(
        Conv2D(384, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    ZFNet.add(
        Conv2D(384, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    ZFNet.add(
        Conv2D(256, (3, 3),
               strides=(1, 1),
               padding='same',
               activation='relu',
               kernel_initializer='uniform'))
    ZFNet.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
    ZFNet.add(Flatten())
    ZFNet.add(Dense(4096, activation='relu'))
    ZFNet.add(Dropout(0.5))
    ZFNet.add(Dense(4096, activation='relu'))
    ZFNet.add(Dropout(0.5))
    ZFNet.add(Dense(1000, activation='softmax'))
    ZFNet.compile(loss='categorical_crossentropy',
                  optimizer='adadelta',
                  metrics=['accuracy'])
    ZFNet.summary()
    save_dir += 'ZFNet.h5'
    return ZFNet
Пример #27
0
Файл: lab3.py Проект: artvit/mo2
def init_lenet5():
    model = Sequential()
    model.add(InputLayer(input_shape=(28, 28, 1)))
    model.add(Conv2D(filters=6, kernel_size=3, activation='relu', padding='same'))
    # model.add(Dropout(rate=0.8))
    model.add(AveragePooling2D())
    model.add(Conv2D(filters=16, kernel_size=3, activation='relu'))
    # model.add(Dropout(rate=0.8))
    model.add(AveragePooling2D())
    model.add(Flatten())
    model.add(Dense(120, activation='relu'))
    model.add(Dense(84, activation='relu'))
    model.add(Dense(10, activation='softmax'))
    print(model.summary())
    return model
# total_data x width x height x channels

x_train = x_train[:, :, :, np.
                  newaxis] / 255.0  # 从60,000 x 28 x 28变为60,000 x 28 x 28 x 1
x_test = x_test[:, :, :,
                np.newaxis] / 255.0  # 从10,000 x 28 x 28到10,000 x 28 x 28 x 1
y_train = to_categorical(y_train)  # 60000*10 10个类别
y_test = to_categorical(y_test)  # 10000*10  10个类别

# 连续模型
model4 = Sequential()
# conv2d会将您的28x28x1图像更改为28x28x64。想象一下这是64个隐藏层单元格。
# 尽可能使用Relu。在每个隐藏层上
model4.add(
    Conv2D(filters=64,
           kernel_size=2,
           padding='same',
           activation='relu',
           input_shape=(28, 28, 1)))
# MaxPooling将减小宽度和高度,因此您无需计算所有单元格。它将大小减小到14x14x64。
model4.add(MaxPooling2D(pool_size=2))
# 最后压扁只是缩小MaxPooling的输出。进入隐藏的12544细胞层。 12544 = 14*14*64
model4.add(Flatten())
# 输出层上的Sigmoid有两个类别  Sigmoid-激励函数
model4.add(Dense(10, activation='softmax'))
# categorical_crossentropy多类别情况  binary_crossentropy 两个类别情况
# 使用adam或rmsprop作为优化器
# 需要accuracy或categorical_accuracy作为检查网络性能的指标。
model4.compile(loss='categorical_crossentropy',
               optimizer='adam',
               metrics=['categorical_accuracy'])
# 10%的训练数据作为验证数据,因此validation_split设置为0.1
# Step 1 Load the Data
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("mnist", one_hot=True)

X_train = mnist.train.images.reshape(-1, 28, 28, 1)
y_train = mnist.train.labels
X_test = mnist.test.images.reshape(-1, 28, 28, 1)
y_test = mnist.test.labels

# Step 2: Build the Network
model = Sequential()
model.add(
    Conv2D(32, (3, 3),
           activation='relu',
           input_shape=(28, 28, 1),
           padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
#model.add(Dropout(0.5))
model.add(Dense(n_classes, activation='softmax'))
#print(model.summary())

# Step 3: Compile the Model
model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])
Пример #30
0
print("TensorFlow version: {}".format(tf.VERSION))

# Generate Testdata
# 100 data points.
# TrainX has values between –1 and 1 and TrainY has 3 times the TrainX and some randomness.
X = np.linspace(0, 10, 100)
Y = X + np.random.randn(*X.shape) * 0.5

#Needed to use the TensorBoard tool to visualize the model training.
tbCallBack = tf.keras.callbacks.TensorBoard(log_dir='./tmp/model_graph',
                                            write_graph=True)

# We shall create a sequential model. All we need is a single connection so we use a Dense layer with linear activation.
model = Sequential()
model.add(Dense(1, input_shape=(1, )))
model.add(Activation("linear"))

# This will take input x and apply weight, w, and bias, b followed by a linear activation to produce output.
# Let’s look at values that the weights are initialized with:
weights = model.layers[0].get_weights()
w_init = weights[0][0][0]
b_init = weights[1][0]
print('Linear regression model is initialized with weights w: %.2f, b: %.2f' %
      (w_init, b_init))
## Linear regression model is initialized with weight w: -0.03, b: 0.00

sgd = SGD(0.01)
model.compile(loss='mse', optimizer=sgd, metrics=['mse'])

H = model.fit(X,
Пример #31
0
class RNNGRU(object):
    """Process data for ingestion."""

    def __init__(
            self, data, sequence_length=20, warmup_steps=50, dropout=0,
            layers=1, patience=10, units=512, display=False):
        """Instantiate the class.

        Args:
            data: Tuple of (x_data, y_data, target_names)
            batch_size: Size of batch
            sequence_length: Length of vectors for for each target
            warmup_steps:

        Returns:
            None

        """
        # Initialize key variables
        self._warmup_steps = warmup_steps
        self._data = data
        self.display = display
        path_checkpoint = '/tmp/checkpoint.keras'
        _layers = int(abs(layers))

        # Delete any stale checkpoint file
        if os.path.exists(path_checkpoint) is True:
            os.remove(path_checkpoint)

        ###################################
        # TensorFlow wizardry
        config = tf.ConfigProto()

        # Don't pre-allocate memory; allocate as-needed
        config.gpu_options.allow_growth = True

        # Only allow a total of half the GPU memory to be allocated
        config.gpu_options.per_process_gpu_memory_fraction = 0.95

        # Crash with DeadlineExceeded instead of hanging forever when your
        # queues get full/empty
        config.operation_timeout_in_ms = 60000

        # Create a session with the above options specified.
        backend.tensorflow_backend.set_session(tf.Session(config=config))
        ###################################

        # Get data
        self._y_current = self._data.close()

        # Create training arrays
        x_train = self._data.vectors_train()
        self._y_train = self._data.classes_train()

        # Create test arrays for VALIDATION and EVALUATION
        xv_test = self._data.vectors_test()
        self._yv_test = self._data.classes_test()

        (self.training_rows, self._training_vector_count) = x_train.shape
        (self.test_rows, _) = xv_test.shape
        (_, self._training_class_count) = self._y_train.shape

        # Print stuff
        print('\n> Numpy Data Type: {}'.format(type(x_train)))
        print("> Numpy Data Shape: {}".format(x_train.shape))
        print("> Numpy Data Row[0]: {}".format(x_train[0]))
        print("> Numpy Data Row[Last]: {}".format(x_train[-1]))
        print('> Numpy Targets Type: {}'.format(type(self._y_train)))
        print("> Numpy Targets Shape: {}".format(self._y_train.shape))

        print('> Number of Samples: {}'.format(self._y_current.shape[0]))
        print('> Number of Training Samples: {}'.format(x_train.shape[0]))
        print('> Number of Training Classes: {}'.format(
            self._training_class_count))
        print('> Number of Test Samples: {}'.format(self.test_rows))
        print("> Training Minimum Value:", np.min(x_train))
        print("> Training Maximum Value:", np.max(x_train))
        print('> Number X signals: {}'.format(self._training_vector_count))
        print('> Number Y signals: {}'.format(self._training_class_count))

        # Print epoch related data
        print('> Epochs:', self._data.epochs())
        print('> Batch Size:', self._data.batch_size())
        print('> Steps:', self._data.epoch_steps())

        # Display estimated memory footprint of training data.
        print("> Data size: {:.2f} Bytes".format(x_train.nbytes))

        '''
        The neural network works best on values roughly between -1 and 1, so we
        need to scale the data before it is being input to the neural network.
        We can use scikit-learn for this.

        We first create a scaler-object for the input-signals.

        Then we detect the range of values from the training-data and scale
        the training-data.
        '''

        self._x_scaler = MinMaxScaler()
        self._x_train_scaled = self._x_scaler.fit_transform(x_train)

        print('> Scaled Training Minimum Value: {}'.format(
            np.min(self._x_train_scaled)))
        print('> Scaled Training Maximum Value: {}'.format(
            np.max(self._x_train_scaled)))

        self._xv_test_scaled = self._x_scaler.transform(xv_test)

        '''
        The target-data comes from the same data-set as the input-signals,
        because it is the weather-data for one of the cities that is merely
        time-shifted. But the target-data could be from a different source with
        different value-ranges, so we create a separate scaler-object for the
        target-data.
        '''

        self._y_scaler = MinMaxScaler()
        self._y_train_scaled = self._y_scaler.fit_transform(self._y_train)
        yv_test_scaled = self._y_scaler.transform(self._yv_test)

        # Data Generator

        '''
        The data-set has now been prepared as 2-dimensional numpy arrays. The
        training-data has almost 300k observations, consisting of 20
        input-signals and 3 output-signals.

        These are the array-shapes of the input and output data:
        '''

        print('> Scaled Training Data Shape: {}'.format(
            self._x_train_scaled.shape))
        print('> Scaled Training Targets Shape: {}'.format(
            self._y_train_scaled.shape))

        # We then create the batch-generator.

        generator = self._batch_generator(
            self._data.batch_size(), sequence_length)

        # Validation Set

        '''
        The neural network trains quickly so we can easily run many training
        epochs. But then there is a risk of overfitting the model to the
        training-set so it does not generalize well to unseen data. We will
        therefore monitor the model's performance on the test-set after each
        epoch and only save the model's weights if the performance is improved
        on the test-set.

        The batch-generator randomly selects a batch of short sequences from
        the training-data and uses that during training. But for the
        validation-data we will instead run through the entire sequence from
        the test-set and measure the prediction accuracy on that entire
        sequence.
        '''

        validation_data = (np.expand_dims(self._xv_test_scaled, axis=0),
                           np.expand_dims(yv_test_scaled, axis=0))

        # Create the Recurrent Neural Network

        self._model = Sequential()

        '''
        We can now add a Gated Recurrent Unit (GRU) to the network. This will
        have 512 outputs for each time-step in the sequence.

        Note that because this is the first layer in the model, Keras needs to
        know the shape of its input, which is a batch of sequences of arbitrary
        length (indicated by None), where each observation has a number of
        input-signals (num_x_signals).
        '''

        self._model.add(GRU(
            units=units,
            return_sequences=True,
            recurrent_dropout=dropout,
            input_shape=(None, self._training_vector_count,)))

        for _ in range(0, _layers):
            self._model.add(GRU(
                units=units,
                recurrent_dropout=dropout,
                return_sequences=True))

        '''
        The GRU outputs a batch of sequences of 512 values. We want to predict
        3 output-signals, so we add a fully-connected (or dense) layer which
        maps 512 values down to only 3 values.

        The output-signals in the data-set have been limited to be between 0
        and 1 using a scaler-object. So we also limit the output of the neural
        network using the Sigmoid activation function, which squashes the
        output to be between 0 and 1.'''

        self._model.add(
            Dense(self._training_class_count, activation='sigmoid'))

        '''
        A problem with using the Sigmoid activation function, is that we can
        now only output values in the same range as the training-data.

        For example, if the training-data only has temperatures between -20
        and +30 degrees, then the scaler-object will map -20 to 0 and +30 to 1.
        So if we limit the output of the neural network to be between 0 and 1
        using the Sigmoid function, this can only be mapped back to temperature
        values between -20 and +30.

        We can use a linear activation function on the output instead. This
        allows for the output to take on arbitrary values. It might work with
        the standard initialization for a simple network architecture, but for
        more complicated network architectures e.g. with more layers, it might
        be necessary to initialize the weights with smaller values to avoid
        NaN values during training. You may need to experiment with this to
        get it working.
        '''

        if False:
            # Maybe use lower init-ranges.
            # init = RandomUniform(minval=-0.05, maxval=0.05)
            init = RandomUniform(minval=-0.05, maxval=0.05)

            self._model.add(Dense(
                self._training_class_count,
                activation='linear',
                kernel_initializer=init))

        # Compile Model

        '''
        This is the optimizer and the beginning learning-rate that we will use.
        We then compile the Keras model so it is ready for training.
        '''
        optimizer = RMSprop(lr=1e-3)
        self._model.compile(
            loss=self._loss_mse_warmup,
            optimizer=optimizer,
            metrics=['accuracy'])

        '''
        This is a very small model with only two layers. The output shape of
        (None, None, 3) means that the model will output a batch with an
        arbitrary number of sequences, each of which has an arbitrary number of
        observations, and each observation has 3 signals. This corresponds to
        the 3 target signals we want to predict.
        '''
        print('> Model Summary:\n')
        print(self._model.summary())

        # Callback Functions

        '''
        During training we want to save checkpoints and log the progress to
        TensorBoard so we create the appropriate callbacks for Keras.

        This is the callback for writing checkpoints during training.
        '''

        callback_checkpoint = ModelCheckpoint(filepath=path_checkpoint,
                                              monitor='val_loss',
                                              verbose=1,
                                              save_weights_only=True,
                                              save_best_only=True)

        '''
        This is the callback for stopping the optimization when performance
        worsens on the validation-set.
        '''

        callback_early_stopping = EarlyStopping(monitor='val_loss',
                                                patience=patience, verbose=1)

        '''
        This is the callback for writing the TensorBoard log during training.
        '''

        callback_tensorboard = TensorBoard(log_dir='/tmp/23_logs/',
                                           histogram_freq=0,
                                           write_graph=False)

        '''
        This callback reduces the learning-rate for the optimizer if the
        validation-loss has not improved since the last epoch
        (as indicated by patience=0). The learning-rate will be reduced by
        multiplying it with the given factor. We set a start learning-rate of
        1e-3 above, so multiplying it by 0.1 gives a learning-rate of 1e-4.
        We don't want the learning-rate to go any lower than this.
        '''

        callback_reduce_lr = ReduceLROnPlateau(monitor='val_loss',
                                               factor=0.1,
                                               min_lr=1e-4,
                                               patience=0,
                                               verbose=1)

        callbacks = [callback_early_stopping,
                     callback_checkpoint,
                     callback_tensorboard,
                     callback_reduce_lr]

        # Train the Recurrent Neural Network

        '''We can now train the neural network.

        Note that a single "epoch" does not correspond to a single processing
        of the training-set, because of how the batch-generator randomly
        selects sub-sequences from the training-set. Instead we have selected
        steps_per_epoch so that one "epoch" is processed in a few minutes.

        With these settings, each "epoch" took about 2.5 minutes to process on
        a GTX 1070. After 14 "epochs" the optimization was stopped because the
        validation-loss had not decreased for 5 "epochs". This optimization
        took about 35 minutes to finish.

        Also note that the loss sometimes becomes NaN (not-a-number). This is
        often resolved by restarting and running the Notebook again. But it may
        also be caused by your neural network architecture, learning-rate,
        batch-size, sequence-length, etc. in which case you may have to modify
        those settings.
        '''

        print('\n> Starting data training\n')

        self._history = self._model.fit_generator(
            generator=generator,
            epochs=self._data.epochs(),
            steps_per_epoch=self._data.epoch_steps(),
            validation_data=validation_data,
            callbacks=callbacks)

        # Load Checkpoint

        '''
        Because we use early-stopping when training the model, it is possible
        that the model's performance has worsened on the test-set for several
        epochs before training was stopped. We therefore reload the last saved
        checkpoint, which should have the best performance on the test-set.
        '''

        print('> Loading model weights')
        if os.path.exists(path_checkpoint):
            self._model.load_weights(path_checkpoint)

        # Performance on Test-Set

        '''
        We can now evaluate the model's performance on the test-set. This
        function expects a batch of data, but we will just use one long
        time-series for the test-set, so we just expand the
        array-dimensionality to create a batch with that one sequence.
        '''

        result = self._model.evaluate(
            x=np.expand_dims(self._xv_test_scaled, axis=0),
            y=np.expand_dims(yv_test_scaled, axis=0))

        print('> Loss (test-set): {}'.format(result))

        # If you have several metrics you can use this instead.
        if False:
            for res, metric in zip(result, self._model.metrics_names):
                print('{0}: {1:.3e}'.format(metric, res))

    def _batch_generator(self, batch_size, sequence_length):
        """Create generator function to create random batches of training-data.

        Args:
            batch_size: Size of batch
            sequence_length: Length of sequence

        Returns:
            (x_batch, y_batch)

        """
        # Infinite loop.
        while True:
            # Allocate a new array for the batch of input-signals.
            x_shape = (
                batch_size, sequence_length, self._training_vector_count)
            x_batch = np.zeros(shape=x_shape, dtype=np.float16)

            # Allocate a new array for the batch of output-signals.
            y_shape = (batch_size, sequence_length, self._training_class_count)
            y_batch = np.zeros(shape=y_shape, dtype=np.float16)

            # Fill the batch with random sequences of data.
            for i in range(batch_size):
                # Get a random start-index.
                # This points somewhere into the training-data.
                idx = np.random.randint(
                    self.training_rows - sequence_length)

                # Copy the sequences of data starting at this index.
                x_batch[i] = self._x_train_scaled[idx:idx+sequence_length]
                y_batch[i] = self._y_train_scaled[idx:idx+sequence_length]

            yield (x_batch, y_batch)

    def _loss_mse_warmup(self, y_true, y_pred):
        """Calculate the Mean Squared Errror.

        Calculate the Mean Squared Error between y_true and y_pred,
        but ignore the beginning "warmup" part of the sequences.

        We will use Mean Squared Error (MSE) as the loss-function that will be
        minimized. This measures how closely the model's output matches the
        true output signals.

        However, at the beginning of a sequence, the model has only seen
        input-signals for a few time-steps, so its generated output may be very
        inaccurate. Using the loss-value for the early time-steps may cause the
        model to distort its later output. We therefore give the model a
        "warmup-period" of 50 time-steps where we don't use its accuracy in the
        loss-function, in hope of improving the accuracy for later time-steps

        Args:
            y_true: Desired output.
            y_pred: Model's output.

        Returns:
            loss_mean: Mean Squared Error

        """
        warmup_steps = self._warmup_steps

        # The shape of both input tensors are:
        # [batch_size, sequence_length, num_y_signals].

        # Ignore the "warmup" parts of the sequences
        # by taking slices of the tensors.
        y_true_slice = y_true[:, warmup_steps:, :]
        y_pred_slice = y_pred[:, warmup_steps:, :]

        # These sliced tensors both have this shape:
        # [batch_size, sequence_length - warmup_steps, num_y_signals]

        # Calculate the MSE loss for each value in these tensors.
        # This outputs a 3-rank tensor of the same shape.
        loss = tf.losses.mean_squared_error(labels=y_true_slice,
                                            predictions=y_pred_slice)

        # Keras may reduce this across the first axis (the batch)
        # but the semantics are unclear, so to be sure we use
        # the loss across the entire tensor, we reduce it to a
        # single scalar with the mean function.
        loss_mean = tf.reduce_mean(loss)

        return loss_mean

    def plot_train(self, start_idx, length=100):
        """Plot the predicted and true output-signals.

        Args:
            start_idx: Start-index for the time-series.
            length: Sequence-length to process and plot.

        Returns:
            None

        """
        # Plot
        self._plot_comparison(start_idx, length=length, train=True)

    def plot_test(self, start_idx, length=100):
        """Plot the predicted and true output-signals.

        Args:
            start_idx: Start-index for the time-series.
            length: Sequence-length to process and plot.

        Returns:
            None

        """
        # Plot
        self._plot_comparison(start_idx, length=length, train=False)

    def _plot_comparison(self, start_idx, length=100, train=True):
        """Plot the predicted and true output-signals.

        Args:
            start_idx: Start-index for the time-series.
            length: Sequence-length to process and plot.
            train: Boolean whether to use training- or test-set.

        Returns:
            None

        """
        # Initialize key variables
        datetimes = {}
        num_train = self.training_rows

        # End-index for the sequences.
        end_idx = start_idx + length

        # Variables for date formatting
        days = mdates.DayLocator()   # Every day
        months = mdates.MonthLocator()  # Every month
        months_format = mdates.DateFormatter('%b %Y')
        days_format = mdates.DateFormatter('%d')

        # Assign other variables dependent on the type of data we are plotting
        if train is True:
            # Use training-data.
            x_values = self._x_train_scaled[start_idx:end_idx]
            y_true = self._y_train[start_idx:end_idx]
            shim = 'Train'

            # Datetimes to use for training
            datetimes[shim] = self._data.datetime()[
                :num_train][start_idx:end_idx]

        else:
            # Scale the data
            x_test_scaled = self._x_scaler.transform(
                self._data.vectors_test_all())

            # Use test-data.
            x_values = x_test_scaled[start_idx:end_idx]
            y_true = self._yv_test[start_idx:end_idx]
            shim = 'Test'

            # Datetimes to use for testing
            datetimes[shim] = self._data.datetime()[
                num_train:][start_idx:end_idx]

        # Input-signals for the model.
        x_values = np.expand_dims(x_values, axis=0)

        # Use the model to predict the output-signals.
        y_pred = self._model.predict(x_values)

        # The output of the model is between 0 and 1.
        # Do an inverse map to get it back to the scale
        # of the original data-set.
        y_pred_rescaled = self._y_scaler.inverse_transform(y_pred[0])

        # For each output-signal.
        for signal in range(len(self._data.labels())):
            # Assign other variables dependent on the type of data plot
            if train is True:
                # Only get current values that are a part of the training data
                current = self._y_current[:num_train][start_idx:end_idx]

                # The number of datetimes for the 'actual' plot must match
                # that of current values
                datetimes['actual'] = self._data.datetime()[
                    :num_train][start_idx:end_idx]

            else:
                # Only get current values that are a part of the test data.
                current = self._y_current[
                    num_train:][start_idx:]

                # The number of datetimes for the 'actual' plot must match
                # that of current values
                datetimes['actual'] = self._data.datetime()[
                    num_train:][start_idx:]

            # Create a filename
            filename = (
                '/tmp/batch_{}_epochs_{}_training_{}_{}_{}_{}.png').format(
                    self._data.batch_size(),
                    self._data.epochs(),
                    num_train,
                    signal,
                    int(time.time()),
                    shim)

            # Get the output-signal predicted by the model.
            signal_pred = y_pred_rescaled[:, signal]

            # Get the true output-signal from the data-set.
            signal_true = y_true[:, signal]

            # Create a new chart
            (fig, axis) = plt.subplots(figsize=(15, 5))

            # Plot and compare the two signals.
            axis.plot(
                datetimes[shim][:len(signal_true)],
                signal_true,
                label='Current +{}'.format(self._data.labels()[signal]))
            axis.plot(
                datetimes[shim][:len(signal_pred)],
                signal_pred,
                label='Prediction')
            axis.plot(datetimes['actual'], current, label='Current')

            # Set plot labels and titles
            axis.set_title('{1}ing Forecast ({0} Future Intervals)'.format(
                self._data.labels()[signal], shim))
            axis.set_ylabel('Values')
            axis.legend(
                bbox_to_anchor=(1.04, 0.5),
                loc='center left', borderaxespad=0)

            # Add gridlines and ticks
            ax = plt.gca()
            ax.grid(True)

            # Add major gridlines
            ax.xaxis.grid(which='major', color='black', alpha=0.2)
            ax.yaxis.grid(which='major', color='black', alpha=0.2)

            # Add minor ticks (They must be turned on first)
            ax.minorticks_on()
            ax.xaxis.grid(which='minor', color='black', alpha=0.1)
            ax.yaxis.grid(which='minor', color='black', alpha=0.1)

            # Format the tick labels
            ax.xaxis.set_major_locator(months)
            ax.xaxis.set_major_formatter(months_format)
            ax.xaxis.set_minor_locator(days)

            # Remove tick marks
            ax.tick_params(axis='both', which='both', length=0)

            # Print day numbers on xaxis for Test data only
            if train is False:
                ax.xaxis.set_minor_formatter(days_format)
                plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)

            # Rotates and right aligns the x labels, and moves the bottom of
            # the axes up to make room for them
            fig.autofmt_xdate()

            # Plot grey box for warmup-period if we are working with training
            # data and the start is within the warmup-period
            if (0 < start_idx < self._warmup_steps):
                if train is True:
                    plt.axvspan(
                        datetimes[shim][start_idx],
                        datetimes[shim][self._warmup_steps],
                        facecolor='black', alpha=0.15)

            # Show and save the image
            if self.display is True:
                fig.savefig(filename, bbox_inches='tight')
                plt.show()
            else:
                fig.savefig(filename, bbox_inches='tight')
            print('> Saving file: {}'.format(filename))

            # Close figure
            plt.close(fig=fig)

    def plot_accuracy(self):
        """Plot the predicted and true output-signals.

        Args:
            None

        Returns:
            None

        """
        # Summarize history for accuracy
        plt.figure(figsize=(15, 5))
        plt.plot(self._history.history['acc'])
        plt.plot(self._history.history['val_acc'])
        plt.title('Model Accuracy')
        plt.ylabel('Accuracy')
        plt.xlabel('Epoch')
        plt.legend(['train', 'test'], loc='upper left')
        plt.show()

        # Summarize history for loss
        plt.figure(figsize=(15, 5))
        plt.plot(self._history.history['loss'])
        plt.plot(self._history.history['val_loss'])
        plt.title('Model loss')
        plt.ylabel('Loss')
        plt.xlabel('Epoch')
        plt.legend(['Train', 'Test'], loc='upper left')
        plt.show()
Пример #32
0
x_test = x_test.astype('float') / 255.0

# one-hot encoding
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

print('y_train[0]:', y_train[0])

# 모델 생성
model = Sequential()

# one-hot encoding 이후 이므로 컬럼수로 정답수 계산. np.unique()하면 2 나옴(0,1뿐이므로)
NB_CLASSES = y_train.shape[1]
print('nb: ', NB_CLASSES)

model.add(
    Dense(units=NB_CLASSES, input_shape=(image_dim, ), activation='softmax'))

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

print('model.fit() 중입니다.')

hist = model.fit(x_train,
                 y_train,
                 validation_split=0.3,
                 epochs=5,
                 batch_size=64,
                 verbose=1)

print('히스토리 목록 보기')
Пример #33
0
Файл: lab3.py Проект: artvit/mo2
def init_model():
    model = Sequential()
    model.add(InputLayer(input_shape=(28, 28, 1)))
    model.add(Conv2D(filters=6, kernel_size=5, activation='relu'))
    # model.add(Conv2D(filters=16, kernel_size=6, activation='relu'))
    model.add(MaxPooling2D(pool_size=2, strides=2))
    model.add(Flatten())
    model.add(Dense(300, activation='relu'))
    model.add(Dense(10, activation='softmax'))
    print(model.summary())
    return model
Пример #34
0
def google_net(size=256, kernel=3):
    model = Sequential()
    model.add(Conv2D(32, (kernel, kernel), 
                     activation='relu', 
                     input_shape=(size, size, 3),
                     strides=2,
                     kernel_regularizer=regularizers.l2(0.01),
                     name='cv1'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (kernel, kernel), 
                     activation='relu',
                     strides=2,
                     kernel_regularizer=regularizers.l2(0.01),
                     name='cv2'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(128, (kernel, kernel), activation='relu', strides=2, name='cv3.3'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(256, kernel_regularizer=regularizers.l2(0.01),  name='features'))
    model.add(Activation('relu'))
    model.add(Dense(3, activation='softmax', name='denseout'))

    print(model.summary())

    model.compile(
        loss='categorical_crossentropy',
        optimizer=RMSprop(lr=1e-4, decay=0.1e-6),
        metrics=['accuracy'])

    return model
def NeuralNetwork(Ntrain, Ntest, pathToTrain, pathToTest):
    #print("Ntrain: ", Ntrain)
    #print("Load Train data: ")
    dataTrain = pd.read_excel(pathToTrain,
                              sheet_name=0,
                              sep='delimiter',
                              header=None)
    dataTrain = dataTrain.values[:Ntrain, :]
    labelsTrain = np.repeat(0, Ntrain)

    for sheet in range(1, 8):
        ms = pd.read_excel(pathToTrain,
                           sheet_name=sheet,
                           sep='delimiter',
                           header=None)
        ms = ms.values[:Ntrain, :]
        dataTrain = np.append(dataTrain, ms)
        labelsTrain = np.append(labelsTrain, np.repeat(sheet, Ntrain))

    dataTrain = dataTrain.reshape(Ntrain * 8, 6, 4)
    #print("Example of matrix input: ", dataTrain[-1])
    labelsTrain = to_categorical(labelsTrain)
    #print(labelsTrain)
    #print("Shape of input: ", dataTrain.shape)
    #print("Shape of labels: ", labelsTrain.shape)

    #print("Load test data: ")
    dataTest = pd.read_excel(pathToTest,
                             sheet_name=0,
                             sep='delimiter',
                             header=None)
    dataTest = dataTest.values[:Ntest, :]
    labelsTest = np.repeat(0, Ntest)

    for sheet in range(1, 8):
        ms = pd.read_excel(pathToTest,
                           sheet_name=sheet,
                           sep='delimiter',
                           header=None)
        ms = ms.values[:Ntest, :]
        dataTest = np.append(dataTest, ms)
        labelsTest = np.append(labelsTest, np.repeat(sheet, Ntest))

    dataTest = dataTest.reshape(Ntest * 8, 6, 4)
    #print("Example of matrix input: ", dataTest[0])
    labelsTest = to_categorical(labelsTest)
    #print(labelsTest)
    #print("Shape of input: ", dataTest.shape)
    #print("Shape of labels: ", labelsTest.shape)

    model = Sequential()
    model.add(Flatten(input_shape=(6, 4)))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(64, activation='relu'))
    # model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.25))
    model.add(Dense(8, activation='softmax'))

    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    model.fit(dataTrain,
              labelsTrain,
              epochs=20,
              batch_size=20,
              verbose=1,
              validation_split=0.2)
    test_loss, test_acc = model.evaluate(dataTest, labelsTest)
    return test_acc
def get_model_1(x,y,Vocab_size,maxlen):
    model = Sequential()
    model.add(Embedding(Vocab_size, 50, input_length=maxlen))
    model.add(LSTM(128, return_sequences=True))
    model.add(LSTM(128))
    model.add(Dense(128, activation='relu'))
    model.add(Dense(Vocab_size))
    model.add(Activation("softmax"))
    print(model.summary())
    model.compile(loss="sparse_categorical_crossentropy", optimizer='adam',  metrics=['accuracy'])
    return model
Пример #37
0
def kerasModel(train_x, test_x, train_y, test_y):
    model = Sequential()

    model.add(Conv2D(24, (5, 5), strides=(2, 2), activation="relu", input_shape=(128, 64, 3)))

    model.add(Conv2D(36, (5, 5), strides=(2, 2), activation="relu"))

    model.add(Conv2D(48, (5, 5), strides=(2, 2), activation="relu"))

    model.add(Conv2D(64, (3, 3), strides=(2, 2), activation="relu"))

    model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(64, activation="relu"))

    model.add(Dense(32, activation="relu"))

    model.add(Dense(1, activation="relu"))
    model.add(Activation('softmax'))
    sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(loss='mse', optimizer=sgd, metrics=['accuracy'])

    model.fit(train_x, train_y, epochs=5)

    # model.compile(loss='mse', optimizer=Adam(lr=0.01, decay=1e-6),metrics=[get_categorical_accuracy_keras])

    # model.fit(train_x,train_y, shuffle=True, nb_epoch=5)

    score = model.evaluate(test_x, test_y, verbose=0)

    print("Accuracy: %.2f%%" % (score[1] * 100))
    return score[1] * 100
def keras_model_fn(hyperparameters):
    """keras_model_fn receives hyperparameters from the training job and returns a compiled keras model.
    The model will be transformed into a TensorFlow Estimator before training and it will be saved in a 
    TensorFlow Serving SavedModel at the end of training.

    Args:
        hyperparameters: The hyperparameters passed to the SageMaker TrainingJob that runs your TensorFlow 
                         training script.
    Returns: A compiled Keras model
    """
    model = Sequential()

    model.add(Conv2D(32, (3, 3), padding='same', name='inputs', input_shape=(HEIGHT, WIDTH, DEPTH)))
    model.add(Activation('relu'))
    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))

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

    model.add(Flatten())
    model.add(Dense(512))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(NUM_CLASSES))
    model.add(Activation('softmax'))
    
    opt = RMSPropOptimizer(learning_rate=hyperparameters['learning_rate'], decay=hyperparameters['decay'])

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

    return model
Пример #39
0
    'data40': [1, 0],
    'data41': [1, 0]
}
labels = DataFrame(
    Data_l,
    columns=[
        'data1', 'data2', 'data3', 'data4', 'data5', 'data6', 'data7', 'data8',
        'data9', 'data10', 'data11', 'data12', 'data13', 'data14', 'data15',
        'data16', 'data17', 'data18', 'data19', 'data20', 'data21', 'data22',
        'data23', 'data24', 'data25', 'data26', 'data27', 'data28', 'data29',
        'data30', 'data31', 'data32', 'data33', 'data34', 'data35', 'data36',
        'data37', 'data38', 'data39', 'data40', 'data41'
    ])

model = Sequential()
model.add(Dense(10, input_dim=21, activation='softmax'))
model.add(Dense(41, activation='linear'))
model.summary()

model.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae'])

model.fit(features, labels)

# serialize model to JSON
model_json = model.to_json()
with open("memocode_ess_q.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("memocode_ess_q.h5")
print("Saved model to disk")
Пример #40
0
class KerasCNN(object):
    """Support vector machine class."""

    # Convolutional Layer 1.
    filter_size1 = 5          # Convolution filters are 5 x 5 pixels.
    num_filters1 = 16         # There are 16 of these filters.

    # Convolutional Layer 2.
    filter_size2 = 5          # Convolution filters are 5 x 5 pixels.
    num_filters2 = 36         # There are 36 of these filters.

    # Fully-connected layer.
    fc_size = 128             # Number of neurons in fully-connected laye

    # Get data from files
    data = MNIST(data_dir='/tmp/data/MNIST/')

    # The number of pixels in each dimension of an image.
    img_size = data.img_size

    # The images are stored in one-dimensional arrays of this length.
    img_size_flat = data.img_size_flat

    # Tuple with height and width of images used to reshape arrays.
    img_shape = data.img_shape

    # Tuple with height, width and depth used to reshape arrays.
    # This is used for reshaping in Keras.
    img_shape_full = data.img_shape_full

    # Number of classes, one class for each of 10 digits.
    num_classes = data.num_classes

    # Number of colour channels for the images: 1 channel for gray-scale.
    num_channels = data.num_channels

    def __init__(self):
        """Instantiate the class.

        Args:
            train_batch_size: Training batch size

        Returns:
            None

        """
        # Initialize variables
        epochs = 2

        """
        print('{0: <{1}} {2}'.format('Encoded X image:', fill, self.x_image))
        """

        # Start construction of the Keras Sequential model.
        self.model = Sequential()

        # Add an input layer which is similar to a feed_dict in TensorFlow.
        # Note that the input-shape must be a tuple containing the image-size.
        self.model.add(InputLayer(input_shape=(self.img_size_flat,)))

        # The input is a flattened array with 784 elements,
        # but the convolutional layers expect images with shape (28, 28, 1)
        self.model.add(Reshape(self.img_shape_full))

        # First convolutional layer with ReLU-activation and max-pooling.
        self.model.add(
            Conv2D(kernel_size=5, strides=1, filters=16, padding='same',
                   activation='relu', name='layer_conv1'))
        self.model.add(MaxPooling2D(pool_size=2, strides=2))

        # Second convolutional layer with ReLU-activation and max-pooling.
        self.model.add(
            Conv2D(kernel_size=5, strides=1, filters=36, padding='same',
                   activation='relu', name='layer_conv2'))
        self.model.add(MaxPooling2D(pool_size=2, strides=2))

        # Flatten the 4-rank output of the convolutional layers
        # to 2-rank that can be input to a fully-connected / dense layer.
        self.model.add(Flatten())

        # First fully-connected / dense layer with ReLU-activation.
        self.model.add(Dense(128, activation='relu'))

        # Last fully-connected / dense layer with softmax-activation
        # for use in classification.
        self.model.add(Dense(self.num_classes, activation='softmax'))

        # Model Compilation

        '''
        The Neural Network has now been defined and must be finalized by adding
        a loss-function, optimizer and performance metrics. This is called
        model "compilation" in Keras.

        We can either define the optimizer using a string, or if we want more
        control of its parameters then we need to instantiate an object. For
        example, we can set the learning-rate.
        '''

        optimizer = Adam(lr=1e-3)

        '''
        For a classification-problem such as MNIST which has 10 possible
        classes, we need to use the loss-function called
        categorical_crossentropy. The performance metric we are interested in
        is the classification accuracy.
        '''

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

        # Training

        '''
        Now that the model has been fully defined with loss-function and
        optimizer, we can train it. This function takes numpy-arrays and
        performs the given number of training epochs using the given
        batch-size. An epoch is one full use of the entire training-set. So for
        10 epochs we would iterate randomly over the entire training-set 10
        times.
        '''

        self.model.fit(x=self.data.x_train,
                       y=self.data.y_train,
                       epochs=epochs, batch_size=128)

        # Evaluation

        '''
        Now that the model has been trained we can test its performance on the
        test-set. This also uses numpy-arrays as input.
        '''

        result = self.model.evaluate(x=self.data.x_test, y=self.data.y_test)

        '''
        Print actual versus predicted values
        '''

        print('\nActual vs Predicted X values')
        start = 0
        stop = 300
        predictions = self.model.predict(self.data.x_test[start:stop])
        for pointer in range(start, stop):
            predicted = np.argmax(predictions[pointer])
            actual = np.argmax(self.data.y_test[pointer])
            print(
                '{}: Actual: {}\tPredicted: {}\tMatch: {}'.format(
                    str(pointer).zfill(3),
                    predicted, actual, predicted == actual))

        '''
        We can print all the performance metrics for the test-set.
        '''
        print('\nPerfomance metrics')
        for name, value in zip(self.model.metrics_names, result):
            print('{} {}'.format(name, value))

        '''
        Print the model summary
        '''

        print('\n\nModel Summary\n\n{}'.format(self.model.summary()))

    def plot_example_errors(self, cls_pred):
        """Plot 9 images in a 3x3 grid.

        Function used to plot 9 images in a 3x3 grid, and writing the true and
        predicted classes below each image.

        Args:
            cls_pred: Array of the predicted class-number for all images in the
                test-set.

        Returns:
            None

        """
        # Boolean array whether the predicted class is incorrect.
        incorrect = (cls_pred != self.data.y_test_cls)

        # Get the images from the test-set that have been
        # incorrectly classified.
        images = self.data.x_test[incorrect]

        # Get the predicted classes for those images.
        cls_pred = cls_pred[incorrect]

        # Get the true classes for those images.
        cls_true = self.data.y_test_cls[incorrect]

        # Plot the first 9 images.
        plot_images(
            images[0:9], self.img_shape, cls_true[0:9], cls_pred=cls_pred[0:9])
Пример #41
0
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
# reshape into X=t and Y=t+1
look_back = 1
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
# calculate root mean squared error
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:, 0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:, 0]))
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

model.summary()

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

history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
Пример #43
0
    def __init__(self,
                 params,
                 restore=None,
                 session=None,
                 use_log=False,
                 image_size=28,
                 image_channel=1,
                 activation='relu',
                 num_labels=10):

        self.image_size = image_size
        self.num_channels = image_channel
        self.num_labels = num_labels

        model = Sequential()
        model.add(Flatten(input_shape=(image_size, image_size, image_channel)))
        # list of all hidden units weights
        self.U = []
        for param in params:
            # add each dense layer, and save a reference to list U
            self.U.append(Dense(param))
            model.add(self.U[-1])
            # ReLU activation
            # model.add(Activation(activation))
            if activation == "arctan":
                model.add(Lambda(lambda x: tf.atan(x)))
            else:
                model.add(Activation(activation))
        self.W = Dense(self.num_labels)
        model.add(self.W)
        # output log probability, used for black-box attack
        if use_log:
            model.add(Activation('softmax'))
        if restore:
            model.load_weights(restore)

        layer_outputs = []
        for layer in model.layers:
            if isinstance(layer, Conv2D) or isinstance(layer, Dense):
                layer_outputs.append(
                    K.function([model.layers[0].input], [layer.output]))

        self.layer_outputs = layer_outputs
        self.model = model
X_test = np.expand_dims((x[:, :, :1000].astype('float32') / 255),
                        axis=3).transpose((2, 0, 1, 3))
X_train = np.expand_dims((x[:, :, 1000:].astype('float32') / 255),
                         axis=3).transpose((2, 0, 1, 3))
Y_test = y[:1000, 0]
Y_train = y[1000:, 0]  # First column marks if data exists

# 6. Preprocess class labels
Y_train = np_utils.to_categorical(Y_train.astype('uint8'), 2)
Y_test = np_utils.to_categorical(Y_test.astype('uint8'), 2)

# 7. Define model architecture

model = Sequential()

model.add(Convolution2D(32, 3, 3, activation='relu',
                        input_shape=(100, 100, 1)))
model.add(Convolution2D(32, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))

# 8. Compile model
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

# 9. Fit model on training data
Пример #45
0
# for i in range (1,5):
# print (cv_images[i])
# plt.imshow(cv_images[i])
# plt.show()

x_train = np.array(cv_images, dtype='float32')

print("DONE with images .....................")
print("x_train_Shape = ", x_train.shape)

batch_size = 200

#Define the Model

cnn_model = Sequential()
cnn_model.add(
    Conv2D(64, kernel_size=(3, 3), input_shape=(32, 32, 3), activation='relu'))
cnn_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
# cnn_model.add(BatchNormalization())
# cnn_model.add(Dropout(0.2))
cnn_model.add(MaxPooling2D(pool_size=2))

cnn_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
cnn_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
#cnn_model.add(BatchNormalization())
#cnn_model.add(Dropout(0.2))
cnn_model.add(MaxPooling2D(pool_size=2))

cnn_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
cnn_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
#cnn_model.add(MaxPooling2D(pool_size=2))
Пример #46
0
    def model(self, params=None):
        """Create the Recurrent Neural Network.

        Args:
            None

        Returns:
            _model: RNN model

        """
        # Initialize key variables
        if params is None:
            _hyperparameters = self.hyperparameters
        else:
            _hyperparameters = params

        # Calculate the steps per epoch
        epoch_steps = int(
            self.training_rows / _hyperparameters['batch_size']) + 1

        # Create the model object
        _model = Sequential()

        '''
        We can now add a Gated Recurrent Unit (GRU) to the network. This will
        have 512 outputs for each time-step in the sequence.

        Note that because this is the first layer in the model, Keras needs to
        know the shape of its input, which is a batch of sequences of arbitrary
        length (indicated by None), where each observation has a number of
        input-signals (num_x_signals).
        '''

        _model.add(GRU(
            units=_hyperparameters['units'],
            return_sequences=True,
            recurrent_dropout=_hyperparameters['dropout'],
            input_shape=(None, self._training_vector_count,)))

        for _ in range(1, _hyperparameters['layers']):
            _model.add(GRU(
                units=_hyperparameters['units'],
                recurrent_dropout=_hyperparameters['dropout'],
                return_sequences=True))

        '''
        The GRU outputs a batch of sequences of 512 values. We want to predict
        3 output-signals, so we add a fully-connected (or dense) layer which
        maps 512 values down to only 3 values.

        The output-signals in the data-set have been limited to be between 0
        and 1 using a scaler-object. So we also limit the output of the neural
        network using the Sigmoid activation function, which squashes the
        output to be between 0 and 1.
        '''

        _model.add(
            Dense(self._training_class_count, activation='sigmoid'))

        '''
        A problem with using the Sigmoid activation function, is that we can
        now only output values in the same range as the training-data.

        For example, if the training-data only has values between -20 and +30,
        then the scaler-object will map -20 to 0 and +30 to 1. So if we limit
        the output of the neural network to be between 0 and 1 using the
        Sigmoid function, this can only be mapped back to values between
        -20 and +30.

        We can use a linear activation function on the output instead. This
        allows for the output to take on arbitrary values. It might work with
        the standard initialization for a simple network architecture, but for
        more complicated network architectures e.g. with more layers, it might
        be necessary to initialize the weights with smaller values to avoid
        NaN values during training. You may need to experiment with this to
        get it working.
        '''

        if False:
            # Maybe use lower init-ranges.
            init = RandomUniform(minval=-0.05, maxval=0.05)

            _model.add(Dense(
                self._training_class_count,
                activation='linear',
                kernel_initializer=init))

        # Compile Model

        '''
        This is the optimizer and the beginning learning-rate that we will use.
        We then compile the Keras model so it is ready for training.
        '''
        optimizer = RMSprop(lr=1e-3)
        _model.compile(
            loss=self._loss_mse_warmup,
            optimizer=optimizer,
            metrics=['accuracy'])

        '''
        This is a very small model with only two layers. The output shape of
        (None, None, 3) means that the model will output a batch with an
        arbitrary number of sequences, each of which has an arbitrary number of
        observations, and each observation has 3 signals. This corresponds to
        the 3 target signals we want to predict.
        '''
        print('\n> Model Summary:\n')
        print(_model.summary())

        # Create the batch-generator.
        generator = self._batch_generator(
            _hyperparameters['batch_size'],
            _hyperparameters['sequence_length'])

        # Validation Set

        '''
        The neural network trains quickly so we can easily run many training
        epochs. But then there is a risk of overfitting the model to the
        training-set so it does not generalize well to unseen data. We will
        therefore monitor the model's performance on the test-set after each
        epoch and only save the model's weights if the performance is improved
        on the test-set.

        The batch-generator randomly selects a batch of short sequences from
        the training-data and uses that during training. But for the
        validation-data we will instead run through the entire sequence from
        the test-set and measure the prediction accuracy on that entire
        sequence.
        '''

        validation_data = (np.expand_dims(self._x_validation_scaled, axis=0),
                           np.expand_dims(self._y_validation_scaled, axis=0))

        # Callback Functions

        '''
        During training we want to save checkpoints and log the progress to
        TensorBoard so we create the appropriate callbacks for Keras.

        This is the callback for writing checkpoints during training.
        '''

        callback_checkpoint = ModelCheckpoint(filepath=self._path_checkpoint,
                                              monitor='val_loss',
                                              verbose=1,
                                              save_weights_only=True,
                                              save_best_only=True)

        '''
        This is the callback for stopping the optimization when performance
        worsens on the validation-set.
        '''

        callback_early_stopping = EarlyStopping(
            monitor='val_loss',
            patience=_hyperparameters['patience'],
            verbose=1)

        '''
        This is the callback for writing the TensorBoard log during training.
        '''

        callback_tensorboard = TensorBoard(log_dir='/tmp/23_logs/',
                                           histogram_freq=0,
                                           write_graph=False)

        '''
        This callback reduces the learning-rate for the optimizer if the
        validation-loss has not improved since the last epoch
        (as indicated by patience=0). The learning-rate will be reduced by
        multiplying it with the given factor. We set a start learning-rate of
        1e-3 above, so multiplying it by 0.1 gives a learning-rate of 1e-4.
        We don't want the learning-rate to go any lower than this.
        '''

        callback_reduce_lr = ReduceLROnPlateau(monitor='val_loss',
                                               factor=0.1,
                                               min_lr=1e-4,
                                               patience=0,
                                               verbose=1)

        callbacks = [callback_early_stopping,
                     callback_checkpoint,
                     callback_tensorboard,
                     callback_reduce_lr]

        # Train the Recurrent Neural Network

        '''We can now train the neural network.

        Note that a single "epoch" does not correspond to a single processing
        of the training-set, because of how the batch-generator randomly
        selects sub-sequences from the training-set. Instead we have selected
        steps_per_epoch so that one "epoch" is processed in a few minutes.

        With these settings, each "epoch" took about 2.5 minutes to process on
        a GTX 1070. After 14 "epochs" the optimization was stopped because the
        validation-loss had not decreased for 5 "epochs". This optimization
        took about 35 minutes to finish.

        Also note that the loss sometimes becomes NaN (not-a-number). This is
        often resolved by restarting and running the Notebook again. But it may
        also be caused by your neural network architecture, learning-rate,
        batch-size, sequence-length, etc. in which case you may have to modify
        those settings.
        '''

        print('\n> Parameters for training\n')
        pprint(_hyperparameters)
        print('\n> Starting data training\n')

        _model.fit_generator(
            generator=generator,
            epochs=_hyperparameters['epochs'],
            steps_per_epoch=epoch_steps,
            validation_data=validation_data,
            callbacks=callbacks)

        # Return
        return _model
Пример #47
0
def model(train_x, train_y, test_x, test_y, epoch):
    '''

    :param train_x: train features
    :param train_y: train labels
    :param test_x:  test features
    :param test_y: test labels
    :param epoch: no. of epochs
    :return:
    '''
    conv_model = Sequential()
    # first layer with input shape (img_rows, img_cols, 1) and 12 filters
    conv_model.add(
        Conv2D(12,
               kernel_size=(3, 3),
               activation='relu',
               input_shape=(img_rows, img_cols, 1)))
    # second layer with 12 filters
    conv_model.add(Conv2D(12, kernel_size=(3, 3), activation='relu'))
    # third layer with 12 filers
    conv_model.add(Conv2D(12, kernel_size=(3, 3), activation='relu'))
    # flatten layer
    conv_model.add(Flatten())
    # adding a Dense layer
    conv_model.add(Dense(100, activation='relu'))
    # adding the final Dense layer with softmax
    conv_model.add(Dense(num_classes, activation='softmax'))

    # compile the model
    conv_model.compile(optimizer=keras.optimizers.Adadelta(),
                       loss='categorical_crossentropy',
                       metrics=['accuracy'])
    print("\n Training the Convolution Neural Network on MNIST data\n")
    # fit the model
    conv_model.fit(train_x,
                   train_y,
                   batch_size=128,
                   epochs=epoch,
                   validation_split=0.1,
                   verbose=2)
    predicted_train_y = conv_model.predict(train_x)
    train_accuracy = (sum(
        np.argmax(predicted_train_y, axis=1) == np.argmax(train_y, axis=1)) /
                      (float(len(train_y))))
    print('Train accuracy : ', train_accuracy)
    predicted_test_y = conv_model.predict(test_x)
    test_accuracy = (
        sum(np.argmax(predicted_test_y, axis=1) == np.argmax(test_y, axis=1)) /
        (float(len(test_y))))
    print('Test accuracy : ', test_accuracy)
    CNN_accuracy = {
        'train_accuracy': train_accuracy,
        'test_accuracy': test_accuracy,
        'epoch': epoch
    }
    return conv_model, CNN_accuracy
Пример #48
0
    def _model(self):
        """Create the Recurrent Neural Network.

        Args:
            None

        Returns:
            _model: RNN model

        """
        # Create the model object
        _model = Sequential()

        '''
        We can now add a Gated Recurrent Unit (GRU) to the network. This will
        have 512 outputs for each time-step in the sequence.

        Note that because this is the first layer in the model, Keras needs to
        know the shape of its input, which is a batch of sequences of arbitrary
        length (indicated by None), where each observation has a number of
        input-signals (num_x_signals).
        '''

        _model.add(GRU(
            units=self._units,
            return_sequences=True,
            recurrent_dropout=self._dropout,
            input_shape=(None, self._training_vector_count,)))

        for _ in range(0, self._layers):
            _model.add(GRU(
                units=self._units,
                recurrent_dropout=self._dropout,
                return_sequences=True))

        '''
        The GRU outputs a batch of sequences of 512 values. We want to predict
        3 output-signals, so we add a fully-connected (or dense) layer which
        maps 512 values down to only 3 values.

        The output-signals in the data-set have been limited to be between 0
        and 1 using a scaler-object. So we also limit the output of the neural
        network using the Sigmoid activation function, which squashes the
        output to be between 0 and 1.'''

        _model.add(
            Dense(self._training_class_count, activation='sigmoid'))

        '''
        A problem with using the Sigmoid activation function, is that we can
        now only output values in the same range as the training-data.

        For example, if the training-data only has temperatures between -20
        and +30 degrees, then the scaler-object will map -20 to 0 and +30 to 1.
        So if we limit the output of the neural network to be between 0 and 1
        using the Sigmoid function, this can only be mapped back to temperature
        values between -20 and +30.

        We can use a linear activation function on the output instead. This
        allows for the output to take on arbitrary values. It might work with
        the standard initialization for a simple network architecture, but for
        more complicated network architectures e.g. with more layers, it might
        be necessary to initialize the weights with smaller values to avoid
        NaN values during training. You may need to experiment with this to
        get it working.
        '''

        if False:
            # Maybe use lower init-ranges.
            # init = RandomUniform(minval=-0.05, maxval=0.05)
            init = RandomUniform(minval=-0.05, maxval=0.05)

            _model.add(Dense(
                self._training_class_count,
                activation='linear',
                kernel_initializer=init))

        # Compile Model

        '''
        This is the optimizer and the beginning learning-rate that we will use.
        We then compile the Keras model so it is ready for training.
        '''
        optimizer = RMSprop(lr=1e-3)
        _model.compile(
            loss=self._loss_mse_warmup,
            optimizer=optimizer,
            metrics=['accuracy'])

        '''
        This is a very small model with only two layers. The output shape of
        (None, None, 3) means that the model will output a batch with an
        arbitrary number of sequences, each of which has an arbitrary number of
        observations, and each observation has 3 signals. This corresponds to
        the 3 target signals we want to predict.
        '''
        print('> Model Summary:\n')
        print(_model.summary())

        # Return
        return _model
class RNNGRU(object):
    """Support vector machine class."""

    def __init__(self,
                 batch_size=64, sequence_length=20, warmup_steps=50,
                 epochs=20, display=False):
        """Instantiate the class.

        Args:
            batch_size: Size of batch
            sequence_length: Length of vectors for for each target
            save: Save charts if True

        Returns:
            None

        """
        # Initialize key variables
        self.target_names = ['Temp', 'WindSpeed', 'Pressure']
        self.warmup_steps = warmup_steps
        self.epochs = epochs
        self.batch_size = batch_size
        self.display = display

        # Get data
        x_data, y_data = self.data()

        print('\n> Numpy Data Type: {}'.format(type(x_data)))
        print("> Numpy Data Shape: {}".format(x_data.shape))
        print("> Numpy Data Row[0]: {}".format(x_data[0]))
        print('> Numpy Targets Type: {}'.format(type(y_data)))
        print("> Numpy Targets Shape: {}".format(y_data.shape))

        '''
        This is the number of observations (aka. data-points or samples) in
        the data-set:
        '''

        num_data = len(x_data)

        '''
        This is the fraction of the data-set that will be used for the
        training-set:
        '''

        train_split = 0.9

        '''
        This is the number of observations in the training-set:
        '''

        self.num_train = int(train_split * num_data)

        '''
        This is the number of observations in the test-set:
        '''

        num_test = num_data - self.num_train

        print('> Number of Samples: {}'.format(num_data))
        print("> Number of Training Samples: {}".format(self.num_train))
        print("> Number of Test Samples: {}".format(num_test))
        print("> Batch Size: {}".format(batch_size))
        steps_per_epoch = int(self.num_train/batch_size)
        print("> Recommended Epoch Steps: {:.2f}".format(steps_per_epoch))

        # Create test and training data
        x_train = x_data[0:self.num_train]
        x_test = x_data[self.num_train:]
        self.y_train = y_data[0:self.num_train]
        self.y_test = y_data[self.num_train:]
        self.num_x_signals = x_data.shape[1]
        self.num_y_signals = y_data.shape[1]

        print("> Training Minimum Value:", np.min(x_train))
        print("> Training Maximum Value:", np.max(x_train))

        '''
        The neural network works best on values roughly between -1 and 1, so we
        need to scale the data before it is being input to the neural network.
        We can use scikit-learn for this.

        We first create a scaler-object for the input-signals.

        Then we detect the range of values from the training-data and scale
        the training-data.
        '''

        x_scaler = MinMaxScaler()
        self.x_train_scaled = x_scaler.fit_transform(x_train)

        print('> Scaled Training Minimum Value: {}'.format(
            np.min(self.x_train_scaled)))
        print('> Scaled Training Maximum Value: {}'.format(
            np.max(self.x_train_scaled)))

        self.x_test_scaled = x_scaler.transform(x_test)

        '''
        The target-data comes from the same data-set as the input-signals,
        because it is the weather-data for one of the cities that is merely
        time-shifted. But the target-data could be from a different source with
        different value-ranges, so we create a separate scaler-object for the
        target-data.
        '''

        self.y_scaler = MinMaxScaler()
        self.y_train_scaled = self.y_scaler.fit_transform(self.y_train)
        y_test_scaled = self.y_scaler.transform(self.y_test)

        # Data Generator

        '''
        The data-set has now been prepared as 2-dimensional numpy arrays. The
        training-data has almost 300k observations, consisting of 20
        input-signals and 3 output-signals.

        These are the array-shapes of the input and output data:
        '''

        print('> Scaled Training Data Shape: {}'.format(
            self.x_train_scaled.shape))
        print('> Scaled Training Targets Shape: {}'.format(
            self.y_train_scaled.shape))

        # We then create the batch-generator.

        generator = self.batch_generator(batch_size, sequence_length)

        # Validation Set

        '''
        The neural network trains quickly so we can easily run many training
        epochs. But then there is a risk of overfitting the model to the
        training-set so it does not generalize well to unseen data. We will
        therefore monitor the model's performance on the test-set after each
        epoch and only save the model's weights if the performance is improved
        on the test-set.

        The batch-generator randomly selects a batch of short sequences from
        the training-data and uses that during training. But for the
        validation-data we will instead run through the entire sequence from
        the test-set and measure the prediction accuracy on that entire
        sequence.
        '''

        validation_data = (np.expand_dims(self.x_test_scaled, axis=0),
                           np.expand_dims(y_test_scaled, axis=0))

        # Create the Recurrent Neural Network

        self.model = Sequential()

        '''
        We can now add a Gated Recurrent Unit (GRU) to the network. This will
        have 512 outputs for each time-step in the sequence.

        Note that because this is the first layer in the model, Keras needs to
        know the shape of its input, which is a batch of sequences of arbitrary
        length (indicated by None), where each observation has a number of
        input-signals (num_x_signals).
        '''

        self.model.add(GRU(
            units=512,
            return_sequences=True,
            input_shape=(None, self.num_x_signals,)))

        '''
        The GRU outputs a batch of sequences of 512 values. We want to predict
        3 output-signals, so we add a fully-connected (or dense) layer which
        maps 512 values down to only 3 values.

        The output-signals in the data-set have been limited to be between 0
        and 1 using a scaler-object. So we also limit the output of the neural
        network using the Sigmoid activation function, which squashes the
        output to be between 0 and 1.'''

        self.model.add(Dense(self.num_y_signals, activation='sigmoid'))

        '''
        A problem with using the Sigmoid activation function, is that we can
        now only output values in the same range as the training-data.

        For example, if the training-data only has temperatures between -20
        and +30 degrees, then the scaler-object will map -20 to 0 and +30 to 1.
        So if we limit the output of the neural network to be between 0 and 1
        using the Sigmoid function, this can only be mapped back to temperature
        values between -20 and +30.

        We can use a linear activation function on the output instead. This
        allows for the output to take on arbitrary values. It might work with
        the standard initialization for a simple network architecture, but for
        more complicated network architectures e.g. with more layers, it might
        be necessary to initialize the weights with smaller values to avoid
        NaN values during training. You may need to experiment with this to
        get it working.
        '''

        if False:
            # Maybe use lower init-ranges.
            init = RandomUniform(minval=-0.05, maxval=0.05)

            self.model.add(Dense(
                self.num_y_signals,
                activation='linear',
                kernel_initializer=init))

        # Compile Model

        '''
        This is the optimizer and the beginning learning-rate that we will use.
        We then compile the Keras model so it is ready for training.
        '''
        optimizer = RMSprop(lr=1e-3)
        self.model.compile(loss=self.loss_mse_warmup, optimizer=optimizer)

        '''
        This is a very small model with only two layers. The output shape of
        (None, None, 3) means that the model will output a batch with an
        arbitrary number of sequences, each of which has an arbitrary number of
        observations, and each observation has 3 signals. This corresponds to
        the 3 target signals we want to predict.
        '''
        print('> Model Summary:\n')
        print(self.model.summary())

        # Callback Functions

        '''
        During training we want to save checkpoints and log the progress to
        TensorBoard so we create the appropriate callbacks for Keras.

        This is the callback for writing checkpoints during training.
        '''

        path_checkpoint = '/tmp/23_checkpoint.keras'
        callback_checkpoint = ModelCheckpoint(filepath=path_checkpoint,
                                              monitor='val_loss',
                                              verbose=1,
                                              save_weights_only=True,
                                              save_best_only=True)

        '''
        This is the callback for stopping the optimization when performance
        worsens on the validation-set.
        '''

        callback_early_stopping = EarlyStopping(monitor='val_loss',
                                                patience=5, verbose=1)

        '''
        This is the callback for writing the TensorBoard log during training.
        '''

        callback_tensorboard = TensorBoard(log_dir='/tmp/23_logs/',
                                           histogram_freq=0,
                                           write_graph=False)

        '''
        This callback reduces the learning-rate for the optimizer if the
        validation-loss has not improved since the last epoch
        (as indicated by patience=0). The learning-rate will be reduced by
        multiplying it with the given factor. We set a start learning-rate of
        1e-3 above, so multiplying it by 0.1 gives a learning-rate of 1e-4.
        We don't want the learning-rate to go any lower than this.
        '''

        callback_reduce_lr = ReduceLROnPlateau(monitor='val_loss',
                                               factor=0.1,
                                               min_lr=1e-4,
                                               patience=0,
                                               verbose=1)

        callbacks = [callback_early_stopping,
                     callback_checkpoint,
                     callback_tensorboard,
                     callback_reduce_lr]

        # Train the Recurrent Neural Network

        '''We can now train the neural network.

        Note that a single "epoch" does not correspond to a single processing
        of the training-set, because of how the batch-generator randomly
        selects sub-sequences from the training-set. Instead we have selected
        steps_per_epoch so that one "epoch" is processed in a few minutes.

        With these settings, each "epoch" took about 2.5 minutes to process on
        a GTX 1070. After 14 "epochs" the optimization was stopped because the
        validation-loss had not decreased for 5 "epochs". This optimization
        took about 35 minutes to finish.

        Also note that the loss sometimes becomes NaN (not-a-number). This is
        often resolved by restarting and running the Notebook again. But it may
        also be caused by your neural network architecture, learning-rate,
        batch-size, sequence-length, etc. in which case you may have to modify
        those settings.
        '''

        self.model.fit_generator(
            generator=generator,
            epochs=self.epochs,
            steps_per_epoch=steps_per_epoch,
            validation_data=validation_data,
            callbacks=callbacks)

        # Load Checkpoint

        '''
        Because we use early-stopping when training the model, it is possible
        that the model's performance has worsened on the test-set for several
        epochs before training was stopped. We therefore reload the last saved
        checkpoint, which should have the best performance on the test-set.
        '''

        try:
            self.model.load_weights(path_checkpoint)
        except Exception as error:
            print('\n> Error trying to load checkpoint.\n\n{}'.format(error))
            sys.exit(0)

        # Performance on Test-Set

        '''
        We can now evaluate the model's performance on the test-set. This
        function expects a batch of data, but we will just use one long
        time-series for the test-set, so we just expand the
        array-dimensionality to create a batch with that one sequence.
        '''

        result = self.model.evaluate(
            x=np.expand_dims(self.x_test_scaled, axis=0),
            y=np.expand_dims(y_test_scaled, axis=0))

        print('> Loss (test-set): {}'.format(result))

        # If you have several metrics you can use this instead.
        if False:
            for res, metric in zip(result, self.model.metrics_names):
                print('{0}: {1:.3e}'.format(metric, res))

    def batch_generator(self, batch_size, sequence_length):
        """Generator function for creating random batches of training-data.

        Args:
            batch_size: Size of batch
            sequence_length: Length of sequence

        Returns:
            (x_batch, y_batch)

        """
        # Infinite loop.
        while True:
            # Allocate a new array for the batch of input-signals.
            x_shape = (batch_size, sequence_length, self.num_x_signals)
            x_batch = np.zeros(shape=x_shape, dtype=np.float16)

            # Allocate a new array for the batch of output-signals.
            y_shape = (batch_size, sequence_length, self.num_y_signals)
            y_batch = np.zeros(shape=y_shape, dtype=np.float16)

            # Fill the batch with random sequences of data.
            for i in range(batch_size):
                # Get a random start-index.
                # This points somewhere into the training-data.
                idx = np.random.randint(self.num_train - sequence_length)

                # Copy the sequences of data starting at this index.
                x_batch[i] = self.x_train_scaled[idx:idx+sequence_length]
                y_batch[i] = self.y_train_scaled[idx:idx+sequence_length]

            yield (x_batch, y_batch)

    def plot_comparison(self, start_idx, length=100, train=True):
        """Plot the predicted and true output-signals.

        Args:
            start_idx: Start-index for the time-series.
            length: Sequence-length to process and plot.
            train: Boolean whether to use training- or test-set.

        Returns:
            None

        """

        if train:
            # Use training-data.
            x_values = self.x_train_scaled
            y_true = self.y_train
            shim = 'Train'
        else:
            # Use test-data.
            x_values = self.x_test_scaled
            y_true = self.y_test
            shim = 'Test'

        # End-index for the sequences.
        end_idx = start_idx + length

        # Select the sequences from the given start-index and
        # of the given length.
        x_values = x_values[start_idx:end_idx]
        y_true = y_true[start_idx:end_idx]

        # Input-signals for the model.
        x_values = np.expand_dims(x_values, axis=0)

        # Use the model to predict the output-signals.
        y_pred = self.model.predict(x_values)

        # The output of the model is between 0 and 1.
        # Do an inverse map to get it back to the scale
        # of the original data-set.
        y_pred_rescaled = self.y_scaler.inverse_transform(y_pred[0])

        # For each output-signal.
        for signal in range(len(self.target_names)):
            # Create a filename
            filename = (
                '/tmp/batch_{}_epochs_{}_training_{}_{}_{}_{}.png').format(
                    self.batch_size, self.epochs, self.num_train, signal,
                    int(time.time()), shim)

            # Get the output-signal predicted by the model.
            signal_pred = y_pred_rescaled[:, signal]

            # Get the true output-signal from the data-set.
            signal_true = y_true[:, signal]

            # Make the plotting-canvas bigger.
            plt.figure(figsize=(15, 5))

            # Plot and compare the two signals.
            plt.plot(signal_true, label='true')
            plt.plot(signal_pred, label='pred')

            # Plot grey box for warmup-period.
            _ = plt.axvspan(
                0, self.warmup_steps, facecolor='black', alpha=0.15)

            # Plot labels etc.
            plt.ylabel(self.target_names[signal])
            plt.legend()

            # Show and save the image
            if self.display is True:
                plt.savefig(filename, bbox_inches='tight')
                plt.show()
            else:
                plt.savefig(filename, bbox_inches='tight')
            print('> Saving file: {}'.format(filename))

    def data(self):
        """Get data to analyze.

        Args:
            None

        Returns:
            (x_data, y_data): X and Y values as numpy arrays

        """
        # Download data
        weather.maybe_download_and_extract()

        # Import data into Pandas dataframe
        pandas_df = weather.load_resampled_data()
        print('\n> First Rows of Data:\n\n{}'.format(pandas_df.head(3)))

        # Print the cities
        cities = weather.cities
        print('\n> Cities: {}'.format(cities))

        # Print dataframe shape
        print(
            '> Dataframe shape (Original): {}'.format(pandas_df.values.shape))

        # The two signals that have missing data. (Columns with Nans)
        pandas_df.drop(('Esbjerg', 'Pressure'), axis=1, inplace=True)
        pandas_df.drop(('Roskilde', 'Pressure'), axis=1, inplace=True)

        # Print dataframe shape
        print('> Dataframe shape (New): {}'.format(pandas_df.values.shape))

        # Verify that the columns have been dropped
        print(
            '\n> First Rows of Updated Data:\n\n{}'.format(pandas_df.head(1)))

        # Add Data

        '''
        We can add some input-signals to the data that may help our model in
        making predictions.

        For example, given just a temperature of 10 degrees Celcius the model
        wouldn't know whether that temperature was measured during the day or
        the night, or during summer or winter. The model would have to infer
        this from the surrounding data-points which might not be very accurate
        for determining whether it's an abnormally warm winter, or an
        abnormally cold summer, or whether it's day or night. So having this
        information could make a big difference in how accurately the model can
        predict the next output.

        Although the data-set does contain the date and time information for
        each observation, it is only used in the index so as to order the data.
        We will therefore add separate input-signals to the data-set for the
        day-of-year (between 1 and 366) and the hour-of-day (between 0 and 23).
        '''

        pandas_df['Various', 'Day'] = pandas_df.index.dayofyear
        pandas_df['Various', 'Hour'] = pandas_df.index.hour

        # Target Data for Prediction

        '''
        We will try and predict the future weather-data for this city.
        '''

        target_city = 'Odense'

        '''
        We will try and predict these signals.
        '''

        self.target_names = ['Temp', 'WindSpeed', 'Pressure']

        '''
        The following is the number of time-steps that we will shift the
        target-data. Our data-set is resampled to have an observation for each
        hour, so there are 24 observations for 24 hours.

        If we want to predict the weather 24 hours into the future, we shift
        the data 24 time-steps. If we want to predict the weather 7 days into
        the future, we shift the data 7 * 24 time-steps.
        '''

        shift_days = 1
        shift_steps = shift_days * 24  # Number of hours.

        # Create a new data-frame with the time-shifted data.

        '''
        Note the negative time-shift!

        We want the future state targets to line up with the timestamp of the
        last value of each sample set.
        '''

        df_targets = pandas_df[
            target_city][self.target_names].shift(-shift_steps)

        '''
        WARNING! You should double-check that you have shifted the data in the
        right direction! We want to predict the future, not the past!

        The shifted data-frame is confusing because Pandas keeps the original

        This is the first shift_steps + 5 rows of the original data-frame:
        '''

        explanatory_hours = shift_steps + 5
        print('\n> First Rows of Updated Data ({} hours):\n\n{}'.format(
            explanatory_hours,
            pandas_df[target_city][self.target_names].head(explanatory_hours)))

        '''
        The following is the first 5 rows of the time-shifted data-frame. This
        should be identical to the last 5 rows shown above from the original
        data, except for the time-stamp.
        '''
        print('\n> First Rows of Shifted Data - Target Labels '
              '(Notice 1980 Dates):\n\n{}'.format(df_targets.head(5)))

        '''
        The time-shifted data-frame has the same length as the original
        data-frame, but the last observations are NaN (not a number) because
        the data has been shifted backwards so we are trying to shift data that
        does not exist in the original data-frame.
        '''
        print('\n> Last Rows of Shifted Data - Target Labels '
              '(Notice 2018 Dates):\n\n{}'.format(df_targets.tail()))

        # NumPy Arrays

        '''
        We now convert the Pandas data-frames to NumPy arrays that can be input
        to the neural network. We also remove the last part of the numpy
        arrays, because the target-data has NaN for the shifted period, and we
        only want to have valid data and we need the same array-shapes for the
        input- and output-data.

        These are the input-signals:
        '''

        x_data = pandas_df.values[0:-shift_steps]
        y_data = df_targets.values[:-shift_steps]

        # Return
        return (x_data, y_data)

    def loss_mse_warmup(self, y_true, y_pred):
        """Calculate the Mean Squared Errror.

        Calculate the Mean Squared Error between y_true and y_pred,
        but ignore the beginning "warmup" part of the sequences.

        We will use Mean Squared Error (MSE) as the loss-function that will be
        minimized. This measures how closely the model's output matches the
        true output signals.

        However, at the beginning of a sequence, the model has only seen
        input-signals for a few time-steps, so its generated output may be very
        inaccurate. Using the loss-value for the early time-steps may cause the
        model to distort its later output. We therefore give the model a
        "warmup-period" of 50 time-steps where we don't use its accuracy in the
        loss-function, in hope of improving the accuracy for later time-steps

        Args:
            y_true: Desired output.
            y_pred: Model's output.

        Returns:
            loss_mean: Mean Squared Error

        """
        warmup_steps = self.warmup_steps

        # The shape of both input tensors are:
        # [batch_size, sequence_length, num_y_signals].

        # Ignore the "warmup" parts of the sequences
        # by taking slices of the tensors.
        y_true_slice = y_true[:, warmup_steps:, :]
        y_pred_slice = y_pred[:, warmup_steps:, :]

        # These sliced tensors both have this shape:
        # [batch_size, sequence_length - warmup_steps, num_y_signals]

        # Calculate the MSE loss for each value in these tensors.
        # This outputs a 3-rank tensor of the same shape.
        loss = tf.losses.mean_squared_error(labels=y_true_slice,
                                            predictions=y_pred_slice)

        # Keras may reduce this across the first axis (the batch)
        # but the semantics are unclear, so to be sure we use
        # the loss across the entire tensor, we reduce it to a
        # single scalar with the mean function.
        loss_mean = tf.reduce_mean(loss)

        return loss_mean