def __init__(self, restore=None, session=None, use_log=False): self.num_channels = 1 self.image_size = 28 self.num_labels = 10 model = Sequential() model.add(Flatten(input_shape=(28, 28, 1))) model.add(Dense(1024)) model.add(Lambda(lambda x: x * 10)) model.add(Activation('softplus')) model.add(Lambda(lambda x: x * 0.1)) model.add(Dense(10)) # 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
def create_network(network_input, n_vocab): print(network_input.shape[0]) print(network_input.shape[1]) print(network_input.shape[2]) print(n_vocab) model = Sequential() model.add( Bidirectional(LSTM(lstm_size, return_sequences=True, recurrent_dropout=r_dropout), input_shape=(network_input.shape[1], network_input.shape[2]))) model.add(Dropout(dropout)) model.add( Bidirectional( LSTM(lstm_size, return_sequences=False, recurrent_dropout=r_dropout))) model.add(Dropout(dropout)) model.add(Dense(n_vocab)) model.add(Activation('softmax')) optimizer = optimizers.rmsprop() model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) if weights_to_load != "": model.load_weights(weights_to_load) return model
def callback(data): print(data.data) vgg16_net = VGG16(weights='imagenet', include_top=False, input_shape=(350, 350, 3)) vgg16_net.trainable = False model = Sequential() model.add(vgg16_net) # Добавляем в модель новый классификатор model.add(Flatten()) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(4)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=1e-5), metrics=['accuracy']) model.load_weights(path + "mnist_model.h5") img = image.load_img(path + 'IMG/' + data.data, target_size=(350, 350)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) / 255 preds = model.predict(x) classes = ['duck', 'none', 'nut', 'wheel'] print(classes[np.argmax(preds)]) pub = rospy.Publisher('class', String, queue_size=2) time.sleep(1) pub.publish(data.data[4] + ' ' + str(classes[np.argmax(preds)]))
def runCNN(): trainImgs = mnist.train_images() trainLabels = mnist.train_labels() print(trainImgs.shape) print(trainLabels.shape) testImgs = mnist.test_images() testLabels = mnist.test_labels() print(testImgs.shape) print(testLabels.shape) trainImgs = (trainImgs / 255) - 0.5 testImgs = (testImgs / 255) - 0.5 trainImgs = np.expand_dims(trainImgs, axis=3) testImgs = np.expand_dims(testImgs, axis=3) print(trainImgs.shape) print(testImgs.shape) model = Sequential() model.add(Conv2D(8, 3, input_shape=(28, 28, 1))) model.add(MaxPooling2D(pool_size=2)) model.add(Flatten()) model.add(Dense(10, activation='softmax')) model.load_weights("mnist_cnn.h5") predict = model.predict(testImgs[0:10]) print(predict) max = np.argmax(predict, axis=1) print(max)
def call_network(text): model = Sequential() model.add(Embedding(num_words, 2, input_length=max_news_len)) model.add(SimpleRNN(8)) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model_save_path='C:\\Users\\Illia\\PycharmProjects\\my_diplom\\Test_network\\best_model\\best_mode_77.h5' model.load_weights(model_save_path) with open('C:\\Users\\Illia\\PycharmProjects\\my_diplom\\Test_network\\best_model\\tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) new_text=[preprocess_text(t) for t in text] sequence = tokenizer.texts_to_sequences(new_text) data = pad_sequences(sequence, maxlen=max_news_len) result = model.predict(data) return result # text = ["Director of the company was fired", "Apple to Start Reopening Stores in Japan This Week", "TikTok's In-App Revenue Skyrockets During Lockdowns", "Coronavirus is propelling Netflix to new heights but is a crash inevitable?"] # # # text2=["May-26-20 01:49AM Dow Jones Futures Jump; Five Titans Near Buy Points In Coronavirus Stock Market Rally Investor's Business Daily", # "May-25-20 01:02PM Gates Foundation Buys Up Amazon, Apple, Twitter Stock; Trims Berkshire Hathaway Stake SmarterAnalyst", # "12:45PM Dow Jones Stocks To Buy And Watch In May 2020; Apple, Microsoft Approach New Buy Points Investor's Business Daily", # "07:58AM Apples Key Weaknesses Investopedia"] # print(call_network(text2))
def load_task_3b_model(): NUM_CLASSES = 2 RESNET50_POOLING_AVERAGE = 'avg' DENSE_LAYER_ACTIVATION = 'softmax' resnet_weights_path = 'models/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' model = Sequential() model.add(ResNet50(include_top=False, pooling=RESNET50_POOLING_AVERAGE, weights=resnet_weights_path)) model.add(Dense(NUM_CLASSES, activation=DENSE_LAYER_ACTIVATION)) model.load_weights("models/trained_models/the_best_model.hdf5") return model
def word_predict(words): #reading preprocessed data input_words = words.lower().split() processed_data_file = open('processed-data','rb') word_to_int = pickle.load(processed_data_file) int_to_word = pickle.load(processed_data_file) seq_length = pickle.load(processed_data_file) n_vocab = pickle.load(processed_data_file) processed_data_file.close() if((len(input_words) != seq_length) and (len(input_words) != seq_length+1)): return '' model = Sequential() # model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True)) #check the significance of input_shape try with X.shape[0], X.shape[1] model.add(LSTM(256, input_shape=(seq_length, 1), return_sequences=True)) #check the significance of input_shape try with X.shape[0], X.shape[1] model.add(Dropout(0.2)) model.add(LSTM(256)) model.add(Dropout(0.2)) # model.add(Dense(y.shape[1], activation='softmax')) #try using linear or ReLU model.add(Dense(n_vocab, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam') #mean squared error # load the network weights # filename = "weights-improvement-38-1.2788.hdf5" filename = "weights-improvement-298-4.2165.hdf5" model.load_weights(filename) model.compile(loss='categorical_crossentropy', optimizer='adam') if(len(input_words)==seq_length+1): X = numpy.reshape([word_to_int[word] for word in input_words[0:seq_length]], (1, seq_length, 1)) X = X / float(n_vocab) y = to_categorical([word_to_int[input_words[seq_length]]], num_classes=n_vocab) model.fit(X, y, epochs=3, batch_size=128) pattern = [word_to_int[word] for word in input_words[1:]] else: pattern = [word_to_int[word] for word in input_words] # print("pattern",pattern) # generate characters for i in range(1): x = numpy.reshape(pattern, (1, len(pattern), 1)) x = x / float(n_vocab) prediction = model.predict(x, verbose=0) index = numpy.argmax(prediction) result = int_to_word[index] pattern.append(index) pattern = pattern[1:len(pattern)] return {"word":result}
def temporal_module(data_dim, timesteps_TIM=10, classes=5, weights_path=None): model = Sequential() model.add( LSTM(3000, return_sequences=False, input_shape=(timesteps_TIM, data_dim))) # model.add(LSTM(3000, return_sequences=False)) model.add(Dense(128, activation='relu')) model.add(Dense(classes, activation='sigmoid')) if weights_path: model.load_weights(weights_path) return model
def __init__(self, restore=None, session=None, use_log=False, use_brelu=False): def bounded_relu(x): return K.relu(x, max_value=1) if use_brelu: activation = bounded_relu else: activation = 'relu' self.num_channels = 1 self.image_size = 28 self.num_labels = 10 model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(28, 28, 1))) model.add(Activation(activation)) model.add(Conv2D(32, (3, 3))) model.add(Activation(activation)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation(activation)) model.add(Conv2D(64, (3, 3))) model.add(Activation(activation)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(200)) model.add(Activation(activation)) model.add(Dense(200)) model.add(Activation(activation)) model.add(Dense(10)) # 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.model = model self.layer_outputs = layer_outputs
def feature_classifier(self, weight_file_path): model = Sequential() model.add(Bidirectional(LSTM(units=cfg.HIDDEN_UNITS, return_sequences=True), input_shape=(cfg.EXPECTED_FRAMES, cfg.NUM_INPUT_TOKENS))) model.add(Dropout(0.4)) model.add(Bidirectional(LSTM(128))) model.add(Dropout(0.4)) model.add(Dense(128, activation='relu')) model.add(Dropout(0.4)) model.add(Dense(self.nb_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.load_weights(weight_file_path) return model
def make_model(): tf.keras.backend.clear_session() loaded = Sequential() # First Block loaded.add( Conv2D(16, activation='relu', kernel_size=(3, 3), padding='same', input_shape=(128, 128, 3))) loaded.add( Conv2D(16, activation='relu', kernel_size=(3, 3), padding='same')) loaded.add(MaxPool2D(pool_size=(3, 3))) # Second Block loaded.add(SeparableConv2D(32, kernel_size=(3, 3), padding='same')) loaded.add(SeparableConv2D(32, kernel_size=(3, 3), padding='same')) loaded.add(SeparableConv2D(32, kernel_size=(3, 3), padding='same')) loaded.add(BatchNormalization()) loaded.add(Activation('relu')) loaded.add(MaxPool2D(pool_size=(3, 3))) # Third Block loaded.add(SeparableConv2D(64, kernel_size=(3, 3), padding='same')) loaded.add(SeparableConv2D(64, kernel_size=(3, 3), padding='same')) loaded.add(BatchNormalization()) loaded.add(Activation('relu')) loaded.add(MaxPool2D(pool_size=(3, 3))) # Forth Block loaded.add(SeparableConv2D(128, kernel_size=(3, 3), padding='same')) loaded.add(SeparableConv2D(128, kernel_size=(3, 3), padding='same')) loaded.add(BatchNormalization()) loaded.add(Activation('relu')) loaded.add(MaxPool2D(pool_size=(3, 3))) loaded.add(Dropout(0.25)) # Fully Connected Layer loaded.add(Flatten()) loaded.add(Dense(units=128, activation='relu')) # Output layer loaded.add(Dense(1, activation='sigmoid')) loaded.load_weights('./flaskblog/BESTWeights.hdf5') return loaded
def build(input_shape_width, input_shape_height, classes, weight_path = '', input_shape_depth = 3): ''' weight_path: a .hdf5 file. If exists, we can load model. ''' # initialize the model model = Sequential() input_shape = (input_shape_height, input_shape_width, input_shape_depth) # if we are using "channels first", update the input shape if K.image_data_format() == 'channels_first': input_shape = (input_shape_depth, input_shape_height, input_shape_width) # first Convolution + relu + pooling layer model.add(Conv2D(filters = 20, kernel_size = (5, 5), padding = 'same', input_shape = input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size = (2, 2), strides=(2, 2))) # second convolutional layer model.add(Conv2D(filters = 50, kernel_size = (5, 5), padding = 'same')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) # Flattening model.add(Flatten()) # Full connection model.add(Dense(units = 500)) model.add(Activation('relu')) # output layer model.add(Dense(units = classes)) model.add(Activation('softmax')) if weight_path: model.load_weights(weight_path) # return the constructed network architecture return model
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
def loadModel(): base_model = Sequential() base_model.add( Convolution2D(32, (11, 11), activation='relu', name='C1', input_shape=(152, 152, 3))) base_model.add( MaxPooling2D(pool_size=3, strides=2, padding='same', name='M2')) base_model.add(Convolution2D(16, (9, 9), activation='relu', name='C3')) base_model.add(LocallyConnected2D(16, (9, 9), activation='relu', name='L4')) base_model.add( LocallyConnected2D(16, (7, 7), strides=2, activation='relu', name='L5')) base_model.add(LocallyConnected2D(16, (5, 5), activation='relu', name='L6')) base_model.add(Flatten(name='F0')) base_model.add(Dense(4096, activation='relu', name='F7')) base_model.add(Dropout(rate=0.5, name='D0')) base_model.add(Dense(8631, activation='softmax', name='F8')) home = str(Path.home()) path = home + '/.deepface/weights/VGGFace2_DeepFace_weights_val-0.9034.h5' if not os.path.isfile(path): print("VGGFace2_DeepFace_weights_val-0.9034.h5 will be downloaded...") url = 'https://github.com/swghosh/DeepFace/releases/download/weights-vggface2-2d-aligned/VGGFace2_DeepFace_weights_val-0.9034.h5.zip' gdown.download(url, path, quiet=False) # unzip VGGFace2_DeepFace_weights_val-0.9034.h5.zip with zipfile.ZipFile(path, 'r') as zip_ref: zip_ref.extractall(home + '/.deepface/weights/') base_model.load_weights(path) inputs = base_model.layers[0].input embeddings = base_model.layers[-3].output outputs = Lambda(lambda x: tf.math.l2_normalize(x, axis=1))(embeddings) # drop F8 and D0. F7 is the representation layer. return Model(inputs=inputs, outputs=outputs)
def launch_neural(self): vgg16_net = VGG16(weights='imagenet', include_top=False, input_shape=(161, 161, 3)) vgg16_net.trainable = False model = Sequential() model.add(vgg16_net) # Добавляем в модель новый классификатор model.add(Flatten()) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(2)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=1e-5), metrics=['accuracy']) model.load_weights("mnist_model.h5") return model
def reloadWeight(): testImgs = mnist.test_images() testLabels = mnist.test_labels() print(testImgs.shape) print(testLabels.shape) testImgs = (testImgs / 255) - 0.5 testImgs = testImgs.reshape((-1, 784)) print(testImgs.shape) model = Sequential() model.add(Dense(64, activation='relu', input_shape=(784, ))) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation='softmax')) model.load_weights("mnist_weight.h5") predict = model.predict(testImgs[0:5]) print(predict) max = np.argmax(predict, axis=1) print(max)
def create_model(): model = Sequential() model.add( LSTM(16, input_shape=(2, 2), return_sequences=True, activation='tanh')) model.add(LSTM(32, return_sequences=True, activation='tanh')) model.add(LSTM(64, return_sequences=True, activation='tanh')) model.add(LSTM(128, return_sequences=True, activation='tanh')) model.add(LSTM(64, return_sequences=True, activation='tanh')) model.add(Dropout(.15)) model.add(LSTM(32, return_sequences=True, activation='tanh')) model.add(Dense(16, activation='sigmoid')) model.add(LSTM(8, return_sequences=True, activation='relu')) model.add(Dense(2, activation='softmax')) model.summary() rms = RMSprop(lr=.01) model.compile(optimizer=rms, loss='categorical_crossentropy', metrics=['accuracy']) if "weights.h5" in os.listdir(".") and train_mode == False: model.load_weights(str("weights.h5")) print("loading saved network: weights.h5") return model
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))
cnn.add(Activation('relu')) cnn.add(MaxPooling2D(pool_size=(2, 2), strides=2)) cnn.add(Flatten()) cnn.add(Dense(64)) cnn.add(Activation('relu')) cnn.add(Dropout(0.4)) cnn.add(Dense(1)) cnn.add(Activation('sigmoid')) cnn.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy', tf.keras.metrics.Recall()]) checkpoint_path = "training_2/cp.ckpt" # Create a callback that saves the model's weights between ephocs cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, save_weights_only=True, verbose=1) start = time.time() cnn.load_weights('cnn-50ep-100batch.h5') #load previous weights #========== train ========== cnn.fit_generator(train_generator, steps_per_epoch=NB_TRAIN_IMG // BATCH_SIZE, epochs=200, validation_data=validation_generator, validation_steps=NB_VALID_IMG // BATCH_SIZE, callbacks=[cp_callback]) end = time.time() print('Processing time:', (end - start) / 60) cnn.save('fullModel04.h5') # save the model with weights
def categorize(): NUM_CLASSES = 16 IMAGE_RESIZE = 224 BATCH_SIZE_TESTING = 1 LOSS_METRICS = ['accuracy'] image_path = sys.argv[1] RESNET50_POOLING_AVERAGE = 'avg' DENSE_LAYER_ACTIVATION = 'softmax' OBJECTIVE_FUNCTION = 'categorical_crossentropy' image_size = IMAGE_RESIZE data_generator = ImageDataGenerator(preprocessing_function = preprocess_input) resnet_weights_path = '../resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' model = Sequential() model.add(ResNet50(include_top = False, pooling = RESNET50_POOLING_AVERAGE, weights = resnet_weights_path)) model.add(Dense(NUM_CLASSES, activation = DENSE_LAYER_ACTIVATION)) model.layers[0].trainable = False sgd = optimizers.SGD(lr = 0.01, decay = 1e-6, momentum = 0.9, nesterov = True) model.compile(optimizer = sgd, loss = OBJECTIVE_FUNCTION, metrics = LOSS_METRICS) # model.load_weights("model_resnet.h5") model.load_weights("../working/resnet_model_20.hdf5") test_generator = data_generator.flow_from_directory( directory = '../test', target_size = (image_size, image_size), batch_size = BATCH_SIZE_TESTING, class_mode = None, shuffle = False, seed = 123 ) # for i in test_generator: # idx = (test_generator.batch_index - 1) * test_generator.batch_size # print(test_generator.filenames[idx : idx + test_generator.batch_size]) class_names = [ '3m_high_tack_spray_adhesive', 'aunt_jemima_original_syrup', 'campbells_chicken_noodle_soup', 'cheez_it_white_cheddar', 'cholula_chipotle_hot_sauce', 'clif_crunch_chocolate_chip', 'coca_cola_glass_bottle', 'detergent', 'expo_marker_red', 'listerine_green', 'nice_honey_roasted_almonds', 'nutrigrain_apple_cinnamon', 'palmolive_green', 'pringles_bbq', 'vo5_extra_body_volumizing_shampoo', 'vo5_split_ends_anti_breakage_shampoo' ] image_names = [str(f) for f in os.listdir('../test/sample_test')] image_names.sort() print image_names image_names = [f[:-4] + ".txt" for f in image_names] result_folder = "../test_results/" test_generator.reset() prediction = model.predict(test_generator, steps = len(test_generator), verbose = 1) print prediction for counter, instance in enumerate(prediction): class_indexes = instance.argsort()[::-1] predicted_classes = [class_names[i] for i in class_indexes] """Ranking of Various Classes""" # with open(result_folder + image_names[counter], 'w') as f: # for item in predicted_classes: # f.write("%s\n" % item) # f.close() # Ranking images ranked_images = [] for image_class in predicted_classes: ranked_images += [image_class+"_"+str(f) for f in os.listdir(os.path.join(image_path, image_class))] with open(result_folder + image_names[counter], 'w') as f: for item in ranked_images: f.write("%s\n" % item) f.close()
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()
Conv2D(64, (1, 3), activation='relu', input_shape=(1, N_channels * 30 * FreqSample // step, 1))) conv.add(MaxPooling2D((1, 2))) conv.add(Conv2D(128, (1, 3), activation='relu')) conv.add(MaxPooling2D((1, 2))) conv.add(Conv2D(256, (1, 3), activation='relu')) conv.add(MaxPooling2D((1, 2))) conv.add(Flatten()) conv.add(Dense(64, activation='relu')) conv.add(Dropout(0.5)) conv.add(Dense(5, activation='softmax')) conv.summary() conv.load_weights(model_file) conv.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print(conv.model.metrics_names) score = conv.evaluate_generator(test_gen, steps=3000) raw_labels.close() raw_features.close() print(score) #print conv.evaluate(X_test_CNN, y_test_CNN) # this returns [test_loss, test_acc] after maximum epochs
grid = ParameterGrid(param_grid) # Accumulate history of all permutations (may be for viewing trend) and keep watching for lowest val_loss as final model for params in grid: print(params) ''' fit_history = model.fit_generator( train_generator, steps_per_epoch=STEPS_PER_EPOCH_TRAINING, epochs=NUM_EPOCHS, validation_data=validation_generator, validation_steps=STEPS_PER_EPOCH_VALIDATION, callbacks=[cb_checkpointer, cb_early_stopper]) model.load_weights("working/best.hdf5") # ### Training Metrics # # One of the default callbacks that is registered when training all deep learning models is the History callback. It records training metrics (training accuracy, training loss, validation loss & validation accuracy) for each epoch. Note that training accuracy & loss during epoch steps are somewhat incomplete information and they are not recorded in history. # # Observe that training uses early stopping, hence metrics is available for epochs run, not for NUM_EPOCHS. print(fit_history.history.keys()) plt.figure(1, figsize=(15, 8)) plt.subplot(221) plt.plot(fit_history.history['acc']) plt.plot(fit_history.history['val_acc']) plt.title('model accuracy')
train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epoch, callbacks=[checkpoint], verbose=1, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size) #model.save_weights("drive/bitirme2/weights/weight2.h5") #%% ############# EVALUATION ############## #evaluation model.load_weights("/content/drive/My Drive/bitirme2/weights/weight23.h5") score = model.evaluate_generator(validation_generator, nb_validation_samples // batch_size, verbose = 1) print("Test Score:", score[0]) print("Test Accuracy:", score[1]) # Plot training & validation accuracy values plt.plot(history_model.history['accuracy']) plt.plot(history_model.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper left') plt.show() # Plot training & validation loss values
cb_early_stopper = EarlyStopping(monitor='val_loss', patience=EARLY_STOP_PATIENCE) cb_checkpointer = ModelCheckpoint(filepath='../best.hdf5', monitor='val_loss', save_best_only=True, mode='auto') print('hi') fit_history = model.fit((train_generator), steps_per_epoch=STEPS_PER_EPOCH_TRAINING, epochs=NUM_EPOCHS, validation_data=(validation_generator), validation_steps=STEPS_PER_EPOCH_VALIDATION, callbacks=[cb_checkpointer, cb_early_stopper]) print('hi2') model.load_weights("../best.hdf5") print(fit_history.history.keys()) plt.figure(1, figsize=(15, 8)) plt.subplot(221) plt.plot(fit_history.history['acc']) plt.plot(fit_history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'valid']) plt.subplot(222) plt.plot(fit_history.history['loss'])
# use_multiprocessing=True, # workers=30, epochs=10, steps_per_epoch=training_generator.__len__(), # validation_data=val_generator.data_generation_NN(batch_size), # validation_steps=val_generator.__len__()) # model_performance.append((i, errors)) # i=i+1 # saved_to_path = tf.contrib.saved_model.save_keras_model( # model, '/home/calvin/model_v14-new_keras.hdf5') # saved_to_path = tf.contrib.saved_model.save_keras_model( # model, '/home/calvin/model_v14-new_keras') model.save_weights('/home/calvin/model_v14-new_keras.hdf5') model.load_weights('/home/calvin/model_v14-new_keras.hdf5', by_name=False) history = model.fit_generator( generator=training_generator, use_multiprocessing=True, workers=1, epochs=20, validation_data=val_generator, ) print(history.history.keys()) # summarize history for accuracy # plt.plot(history.history['acc']) # plt.plot(history.history['val_acc']) # plt.title('model validation accuracy') # plt.ylabel('accuracy')
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
# 我们使用adam以0.001的learning rate进行优化 optimizer = Adam(lr=1e-3) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) # 我们来看一下模型的结构,一共90k左右可训练的变量 model.summary() # 建立一个权重的存储点 path_checkpoint = 'sentiment_checkpoint.keras' checkpoint = ModelCheckpoint(filepath=path_checkpoint, monitor='val_loss', verbose=1, save_weights_only=True, save_best_only=True) # 尝试加载已训练模型 try: model.load_weights(path_checkpoint) except Exception as e: print(e) # 定义early stoping如果3个epoch内validation loss没有改善则停止训练 earlystopping = EarlyStopping(monitor='val_loss', patience=5, verbose=1) # 自动降低learning rate lr_reduction = ReduceLROnPlateau(monitor='val_loss', factor=0.1, min_lr=1e-8, patience=0, verbose=1) # 定义callback函数 callbacks = [ earlystopping, checkpoint, lr_reduction ]
# model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) # Viewing model_configuration # model.summary() # model.get_config() # model.layers[0].get_config() # model.layers[0].input_shape # model.layers[0].output_shape # model.layers[0].get_weights() # np.shape(model.layers[0].get_weights()[0]) # model.layers[0].trainable # load model dirr = "Downloads/DA/" model.load_weights(dirr + 'model.hdf5') #model.load_model('model.hdf5') #labels_name={'center':0,'left':1,'right':2} directions = {'center', 'left', 'right'} # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (720, 480) idx = [0, 0, 0] print("Thu bam nut") while True: buttonState = IO.input(buttonPin) # Neu button dang nhan if buttonState == False:
to_predict = [] classes = [ 'Pushing Two Fingers Away', 'Pushing Hand Away', 'Doing other things', 'Turning Hand Clockwise', 'Zooming In With Two Fingers', 'Sliding Two Fingers Left', 'Stop Sign', 'Pulling Two Fingers In', 'Drumming Fingers', 'Sliding Two Fingers Right', 'Sliding Two Fingers Down', 'No gesture', 'Rolling Hand Backward', 'Swiping Down', 'Rolling Hand Forward', 'Turning Hand Counterclockwise', 'Thumb Down', 'Swiping Up', 'Zooming Out With Full Hand', 'Shaking Hand', 'Thumb Up', 'Zooming In With Full Hand', 'Swiping Right', 'Zooming Out With Two Fingers', 'Swiping Left', 'Sliding Two Fingers Up', 'Pulling Hand In' ] model.load_weights('main.h5') num_frames = 0 cap = cv2.VideoCapture(0) cap.set(12, 50) cap.set(6, 10) preds = [] classe = '' import time while (True): # Capture frame-by-frame ret, frame = cap.read() frame_cp = frame
model.add(Dense(16)) model.add(Dense(1)) # adam = Adam(lr=lrate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=decay_rate, amsgrad=False) model.compile(optimizer='adam', loss='mse') # history = model.fit(xtrain, ytrain, epochs=epoch, validation_data=(xval, yval), # callbacks=callbacks, batch_size=200, shuffle=False) # to load only the weights you must define the model as above # model.load_weights('weights\Best_2019_03_28 02_07_59.h5') # for both vol and closing price # model.fit with callbacks save only the weights model.load_weights(filepath) # # model = load_model(f"model\model55.h5") # plt.plot(history.history['loss'], label='loss') # plt.plot(history.history['val_loss'], label='Val_loss') # plt.legend() # # plt.pause(2) # # plt.clf() # plt.show() print(model.summary()) pred = model.predict(xtest) print(type(pred), ytest.shape, sep=sp, end=sp) # actual, prediction = [], [] prediction = scaler.inverse_transform(pred).reshape(-1) actual = scaler.inverse_transform(ytest).reshape(-1)
50, 3) + img xtrain[c] = xtrain[c] - np.mean(xtrain[c]) ytrain[c] = labels_cat[NB_CLASSES] c = c + 1 print('Train data generation .. done') return xtrain, ytrain """ Start a training session + save """ print("Start a training session") if (CONTINUE_TRAINING == True): model = model_from_json(open(f'{RESULTS_PATH}/model_conv3D.json').read()) model.load_weights(f'{RESULTS_PATH}/weights_conv3D.h5') model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) for serie in range(NB_SESSION): # memory management if (serie != 0): del xtrain del ytrain xtrain = np.zeros(shape=((NB_CLASSES + 1) * NB_VIDEOS_BY_CLASS_TRAIN, LENGTH_VIDEO, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS)) ytrain = np.zeros(shape=((NB_CLASSES + 1) * NB_VIDEOS_BY_CLASS_TRAIN,
def build_model(): # CREATING THE RECURRENT NEURAL NETWORK model = Sequential() # Add a Gated Recurrent Network to the network, has 512 outputs for each time-step # Input shape requires the shape of its input, None means of arbitrary length model.add( GRU(units=512, return_sequences=True, input_shape=( None, num_x_signals, ))) # As output signals are limited between 0 and 1 we must do the same for the output from the neural network model.add(Dense(num_y_signals, activation='sigmoid')) # LOSS FUNCTION global warmup_steps warmup_steps = 50 # Defining the start Learning Rate we will be using optimizer = tf.keras.optimizers.RMSprop(lr=1e-10) # Compiles the model: model.compile(loss=loss_mse_warmup, optimizer=optimizer) model.summary() # Callback for writing checkpoints during training path_checkpoint = 'checkpoint.keras' callback_checkpoint = ModelCheckpoint(filepath=path_checkpoint, monitor='val_loss', verbose=1, save_weights_only=True, save_best_only=True) # Callback for stopping optimization when performance worsens on the validation set callback_early_stopping = EarlyStopping(monitor='val_loss', patience=5, verbose=1) # Callback for writing the TensorBoard log during training callback_tensorboard = TensorBoard(log_dir='./23_logs/', histogram_freq=0, write_graph=False) # Callback reduces learning rate for the optimizer if the validation-loss has not improved since the last epoch 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 ] model.fit(x=generator, epochs=20, steps_per_epoch=100, validation_data=validation_data, callbacks=callbacks) try: model.load_weights(path_checkpoint) except Exception as error: print("Error trying to load checkpoint.") print(error) result = model.evaluate(x=np.expand_dims(x_test_scaled, axis=0), y=np.expand_dims(y_test_scaled, axis=0)) print("loss (test-set):", result)