def classifyMammograms(): X, y = readData() X = numpy.array(X) y = numpy.array(y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=123, shuffle=True) y_train = to_categorical(y_train) y_test = to_categorical(y_test) model = Sequential() model.add( Dense(128, activation='relu', input_dim=len(X[0]), kernel_regularizer='l2', kernel_initializer=he_normal(seed=None))) model.add(Dense(128)) model.add(Dense(64, activation='relu')) model.add(Dense(64)) model.add(Dense(32, activation='relu')) model.add(Dense(32)) model.add(Dense(16, activation='relu')) model.add(Dense(16)) model.add(Dense(8, activation='relu')) model.add(Dense(4)) model.add(Dense(2, activation='sigmoid')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) filepath = "model.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min') earlystopping = EarlyStopping(monitor='loss', patience=20, restore_best_weights=True) desired_callbacks = [checkpoint, earlystopping] # history = model.fit(X_train, y_train, validation_split=0.2, batch_size=50, epochs=1000, shuffle=True, # callbacks=desired_callbacks) # plt.plot(history.history['loss']) # plt.plot(history.history['val_loss']) # plt.title('model loss') # plt.ylabel('loss') # plt.xlabel('epoch') # plt.legend(['train', 'test'], loc='upper left') # plt.savefig("loss.jpg") model = load_model("model.hdf5") model.summary() scores = model.evaluate(X_train, y_train, verbose=0) print( 'Accuracy on training data: {}% \n Error on training data: {}'.format( scores[1], 1 - scores[1])) scores2 = model.evaluate(X_test, y_test, verbose=0) print('Accuracy on test data: {}% \n Error on test data: {}'.format( scores2[1], 1 - scores2[1]))
def train(train_X, train_y, test_X, test_y, num_of_features, classes, layer_det, id, num_epochs=30, batch_size=100): # Train a neural network # Saves a model to disk train_y = to_categorical(train_y) #converts to one hot test_y = to_categorical(test_y) model = Sequential() model.add(Dense(layer_det[0], input_dim=num_of_features, activation='relu')) model.add(layers.Dropout(0.3, noise_shape=None, seed=None)) model.add(Dense(layer_det[1], activation='relu')) model.add(layers.Dropout(0.2, noise_shape=None, seed=None)) model.add(Dense(layer_det[2], activation='relu')) model.add(layers.Dropout(0.2, noise_shape=None, seed=None)) model.add(Dense(classes, activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) # Fit the model model.fit(train_X, train_y, epochs=num_epochs, batch_size=batch_size) score = model.evaluate(train_X, train_y, verbose=0) print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100)) model.save('model'+str(id)+'.h5') # creates a HDF5 file 'my_model.h5' score = model.evaluate(test_X,test_y, verbose=0) print("model"+str(id)+"====== %s: %.2f%%" % (model.metrics_names[1], score[1]*100))
class SarcasmCNN: """ End-to-end convolutional neural network pipeline for sarcasm classification on tweet corpus """ def __init__(self, data, vocab_processor): """ Constructor for SarcasmCNN Params: data """ # instantiate model (self.X_train, self.y_train), (self.X_test, self.y_test) = data self.vocab_processor = vocab_processor self.epochs = EPOCHS self.batch_size = BATCH_SIZE self.history = None self.loss = None self.accuracy = None self.model = Sequential() self._add_model_layers() def _add_model_layers(self): self.model.add(layers.Embedding(input_dim=len(self.vocab_processor.vocabulary_), output_dim=self.X_train.shape[1])) self.model.add(layers.Conv1D(128, 5, activation='relu')) self.model.add(layers.GlobalMaxPooling1D()) self.model.add(layers.Dense(10, activation='relu')) self.model.add(layers.Dense(1, activation='sigmoid')) def fit(self): self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) self.model.summary() self.history = self.model.fit(self.X_train, self.y_train, epochs=self.epochs, verbose=True, validation_data=(self.X_test, self.y_test), batch_size=self.batch_size) def evaluate(self, X, y): loss, accuracy = self.model.evaluate(X, y, verbose=False) print("Testing Accuracy: {:.4f}".format(accuracy)) print(f"Testing Loss: {loss:.4f}") def run(self): self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) self.model.summary() self.history = self.model.fit(self.X_train, self.y_train, epochs=self.epochs, verbose=True, validation_data=(self.X_test, self.y_test), batch_size=self.batch_size) self.loss, self.accuracy = self.model.evaluate(self.X_test, self.y_test, verbose=False) print("Testing Accuracy: {:.4f}".format(self.accuracy)) print(f"Testing Loss: {self.loss:.4f}")
def find_best_for_sequential(x_train, x_test): print(end="\n\n") max_score = 0 best = [0, 0] for k in range(10): model = Sequential() num = randint(100, 250) num2 = randint(20, num - 20) model.add(Dense(num, activation="relu", input_dim=dict_len)) model.add(Dense(num2, activation="relu")) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=metrics) for _ in range(2): model.fit(x_train, y_train, epochs=5, batch_size=200, validation_split=0.1, verbose=0) srs = model.evaluate(x_test, y_test, verbose=0) if max_score < srs[3]: max_score = srs[3] best = [num, num2] clear_session() print("Best first layer for sequential:", best[0]) print("Best second layer for sequential:", best[1]) return best
def scorensave_Keras(X, y): """ Given a full training set (no splits), this function creates, scores and saves a Keras Classifer model for use in predictions NOTE: Intended only for use after proper scoring of model using score_Keras (but not required) """ X_dim = X.shape[1] # create model model = Sequential() model.add(Dense(12, input_dim=X_dim, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, y, epochs=150, batch_size=10) # evaluate the model scores = model.evaluate(X, y) print('150 epochs, 10 batch_size') print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100)) end_time = time.time() print("total time: ", end_time - start_time) model.save(K_filename) print("Saved Keras model to " + K_filename)
def classify_wine_type(wines_df): x = wines_df.iloc[:, 0:11] y = np.ravel(wines_df.type) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42) scaler = StandardScaler().fit(x_train) x_train = scaler.transform(x_train) x_test = scaler.transform(x_test) model = Sequential() model.add(Dense(12, activation='relu', input_shape=(11, ))) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # print_model(model) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5, batch_size=30, verbose=2) # Return the prediction score # y_pred = model.predict(X_test, verbose=1) # Return the prediction class y_pred = model.predict_classes(x_test, verbose=1) # The score is a list that holds the combination of the loss and the accuracy score = model.evaluate(x_test, y_test, verbose=1) print(f'score is: {score}')
def evaluate_model(trainX, trainy, testX, testy): global best_accuracy verbose, epochs, batch_size = 0, 10, 32 # n_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], trainy.shape[1] model = Sequential() # model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_timesteps,n_features))) (x_train.shape[1],1) model.add( Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(trainX.shape[1], 1))) model.add(Conv1D(filters=64, kernel_size=3, activation='relu')) model.add(Dropout(0.5)) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) model.add(Dense(100, activation='relu')) model.add(Dense(trainy.shape[1], activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # fit network model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=1) # evaluate model _, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=0) if accuracy > best_accuracy: best_accuracy = accuracy model.save(BestModleFilePath) return accuracy
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 main(): (x_train, y_train), (x_test, y_test) = fashion_mnist.load_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 y_train = utils.to_categorical(y_train, 10) y_test = utils.to_categorical(y_test, 10) model = Sequential() model.add(Dense(784, input_dim=784, activation="relu")) model.add(Dense(10, activation="softmax")) model.compile(loss="categorical_crossentropy", optimizer="SGD", metrics=["accuracy"]) model.summary() callback = [ TensorBoard(log_dir='logs', histogram_freq=1, write_images=True) ] model.fit(x_train, y_train, batch_size=200, epochs=300, verbose=1, validation_split=0.2, callbacks=callback) model.save("fashion_model.h5") score = model.evaluate(x_test, y_test, verbose=1) print("Accuracy on test data is", score[1] * 100, "percent")
def plotNetwork(self, train_X, train_Y, test_X, test_y, lr, e, b, r): model = Sequential() #to prevent overfitting, we use regularizer, dropout Regularizer = l2(r) #add a LSTM layer with 100 units, expecting the corresponding input and output size model.add(LSTM(100, input_shape=(train_X.shape[1], train_X.shape[2]),kernel_regularizer=Regularizer , recurrent_regularizer=Regularizer , bias_regularizer=Regularizer , activity_regularizer=Regularizer, dropout=0.2, recurrent_dropout=0.3)) model.add(keras.layers.Dense(1,activation=tf.keras.activations.softsign)) opt = keras.optimizers.Adam(lr) model.compile(loss='mae', optimizer=opt, metrics=['accuracy']) score, accuracy = model.evaluate(self.test_X, self.test_y, verbose=0) # fit network history = model.fit(self.train_X, self.train_y, epochs=e, batch_size=b, validation_data=(self.test_X, self.test_y), verbose=2, shuffle=False) # plot history plt.title('model loss') plt.plot(history.history['loss'], label='train') plt.plot(history.history['val_loss'], label='test') textstr = ('epochs=' + str(e) + '\n' + 'batch_size=' + str(b) + '\n' + 'regularizer rate=' + str(r) + '\n' + 'learning rate=' + str(lr) + '\n' + 'regularizer=' + str(r)) xmin, xmax, ymin, ymax = plt.axis() #get the max value of y_axis so we can place parameter information at the approapriate position plt.text(0.5*e, 0.7*ymax, textstr) plt.xlabel('epochs') plt.ylabel('loss') plt.legend() plt.show() return model
def evaluate_fitness(_model: Sequential, _history): # evaluate (though this doesnt account for inverting the result) _, train_acc = _model.evaluate(train_X, train_y, BATCH_SIZE, verbose=2) _, test_acc = _model.evaluate(test_X, test_y, BATCH_SIZE, verbose=2) print('Train: %.3f, Test: %.3f' % (train_acc, test_acc)) plt.subplot(211) plt.title('loss') plt.plot(_history.history['loss'], label='train') plt.plot(_history.history['val_loss'], label='test') plt.legend() plt.subplot(212) plt.title('acc') plt.plot(_history.history['acc'], label='train') plt.plot(_history.history['val_acc'], label='test') plt.legend() plt.show()
def generate(self): train = pd.read_csv(self.train_path) test = pd.read_csv(self.test_path) X_train, y_train, _ = self.preprocess_data(train) X_test, y_test, _ = self.preprocess_data(test) model = Sequential() model.add( Conv2D(kernel_size=5, strides=1, filters=32, activation='relu', name='conv_layer1', input_shape=self.img_shape_keras, padding='same')) model.add(MaxPooling2D(pool_size=2, strides=2)) model.add(Dropout(0.5)) model.add( Conv2D(kernel_size=5, strides=1, filters=64, activation='relu', name='conv_layer2', padding='same')) model.add(MaxPooling2D(pool_size=2, strides=2)) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(self.num_classes, activation='softmax')) optimizer = Adam(lr=0.0001) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) early_stopping_monitor = EarlyStopping(patience=2, monitor='val_acc') checkpoint = ModelCheckpoint(filepath='model.h5', monitor='val_acc', verbose=1, save_best_only=True, mode='max') history = model.fit(X_train, y_train, validation_split=0.3, batch_size=200, epochs=50, callbacks=[early_stopping_monitor, checkpoint], verbose=2) model.summary() score = model.evaluate(X_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) self.plot_accuracy(history) self.plot_loss(history)
def _model(train, test, target): optimizer = Nadam(lr=0.0002) reshape_X_train, reshape_X_test, reshape_y_train, reshape_y_test, reshape_scaled_train, validation = selfprocessing( train, test, target) num = train.shape[1] print(num) model = Sequential() model.add( LSTM(11, activation='linear', return_sequences=True, input_shape=(1, num))) model.add(Dropout(0.4)) model.add( LSTM(22, activation='linear', return_sequences=True, input_shape=(1, num))) model.add(Dropout(0.4)) model.add( LSTM(44, activation='linear', return_sequences=True, input_shape=(1, num))) model.add(Dropout(0.4)) model.add(LSTM(88, activation='linear', input_shape=(1, num))) model.add(Dropout(0.1)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='mae', optimizer=optimizer, metrics=['mse']) result = model.fit(reshape_X_train, reshape_y_train, epochs=30000, shuffle=False, callbacks=[ EarlyStopping(monitor='loss', min_delta=0.001, mode='min', patience=30) ], batch_size=1280) evaluate = model.evaluate(reshape_X_test, reshape_y_test) pred = model.predict(validation) old = model.predict(reshape_scaled_train) print(minmax.inverse_transform(pred)) print(evaluate) plt.figure(1) plt.plot(result.history['loss']) plt.title('loss' + str(round(result.history['loss'][-1], 6))) plt.show() plt.figure(2) plt.plot(minmax.inverse_transform(old)) plt.plot(minmax.inverse_transform(target)) plt.show() plt.figure(3) plt.plot(minmax.inverse_transform(pred)) plt.show()
def traning(): ''' 训练函数 :return: ''' num_of_word = 50 words_use = 40000 #初始化模型并加载 data = Data(path="../data/") w2v = Word2Vec(len=num_of_word, path="../third/models") #构建训练数据集和训练结果集 sentences = data.negative_data + data.neural_data + data.positive_data traning_seq = w2v.convert_sentences_to_seqences(sentences) traning_res = data.create_classs() print(traning_seq) print(traning_res) #创建输入层向量 embding_dimen = w2v.w2v_model["银行"].shape[0] embding_mat = np.zeros((words_use, embding_dimen)) for i in range(num_of_word): embding_mat[i, :] = w2v.w2v_model[w2v.w2v_model.index2word[i]] embding_mat = embding_mat.astype('float32') traning_seq[traning_seq >= words_use] = 0 #创建模型 model = Sequential() model.add( Embedding(words_use, embding_dimen, weights=[embding_mat], input_length=num_of_word, trainable=False)) model.add(GRU(units=32, return_sequences=True)) model.add(GRU(units=16, return_sequences=False)) model.add(Dense(3, activation='softmax')) #模型编译 model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) #模型训练 使用后10个数据测试 model.fit(traning_seq[:-10], traning_res[:-10], validation_split=0.1, epochs=40, batch_size=128) #使用后10个数据测试 result = model.evaluate(traning_seq[-10:], traning_res[-10:]) print('Accuracy:{0:.3%}'.format(result[1]))
def grumdl(xtrain, ytrain, xtest, ytest, num_classes, batch_size, epochs, callbacks, imgrows, ismodelsaved=False, tl=False): if ismodelsaved == False: # model definition mdl = Sequential() mdl.add(layers.GRU(92)) mdl.add(layers.Dense(92)) mdl.add(layers.BatchNormalization()) mdl.add(layers.Dense(92)) mdl.add(layers.Dropout(0.25)) mdl.add(layers.Dense(2, activation='softmax')) mdl.compile(loss=binary_crossentropy, optimizer=tf.keras.optimizers.RMSprop(0.001, rho=0.9), metrics=['accuracy']) histmdl = mdl.fit(xtrain, ytrain, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(xtest, ytest), callbacks=callbacks) score = mdl.evaluate(xtest, ytest, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) # # display learning curves if True: plt.figure() plt.plot(histmdl.history['loss'], label='train loss') plt.plot(histmdl.history['val_loss'], label='test loss') plt.title('Learning Curves') plt.xlabel('epochs') plt.ylabel('loss') plt.legend() plt.show() else: if imgrows == 4: mdl = tf.keras.models.load_model(flpath + 'saved_model_4x23/gru_4x23') else: if tl: mdl = tf.keras.models.load_model( flpath + 'saved_model_guideseq_8x23/gru_8x23') else: mdl = tf.keras.models.load_model( flpath + 'saved_model_crispr_8x23/grucrispr_8x23') print("GRU: Done") return mdl
def run(): 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 = trainImgs.reshape((-1, 784)) testImgs = testImgs.reshape((-1, 784)) print(trainImgs.shape) 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.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'], ) model.fit( trainImgs, # training data to_categorical(trainLabels), # training targets epochs=3, batch_size=32, validation_data=(testImgs, to_categorical(testLabels))) # evaluate test data model.evaluate(testImgs, to_categorical(testLabels)) # save model model.save_weights('mnist_weight.h5')
def create_model(): import time name = "CATS_VS_DOGS_CNN-{}".format(int(time.time())) tensorboard = TensorBoard(log_dir='logs\\{}'.format(name)) x_train = pickle.load(open("x_train.pickle", "rb")) y_train = pickle.load(open("y_train.pickle", "rb")) x_test = pickle.load(open("x_test.pickle", "rb")) y_test = pickle.load(open("y_test.pickle", "rb")) x_train = np.array(x_train) y_train = np.array(y_train) x_test = np.array(x_test) y_test = np.array(y_test) x_train = x_train / 255.0 x_test = x_test / 255.0 model = Sequential() model.add(Conv2D(64, (3, 3), input_shape=x_train.shape[1:])) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (3, 3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (3, 3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(256, (3, 3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(512)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=['accuracy']) model.summary() import time start_time = time.time() model.fit(x_train, y_train, batch_size=32, epochs=15, validation_split=0.35, callbacks=[tensorboard]) model.save('network.model') print("--- %s seconds ---" % (time.time() - start_time)) print('\n# Evaluate on test data') results = model.evaluate(x_test, y_test, batch_size=32, callbacks=[tensorboard]) print('test loss, test acc:', results)
def train_model(train_data_input, train_coordinates): print(train_coordinates.shape[1]) model = Sequential() '''Choose a model to train''' # '''1. CNN model''' # model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(train_data_input.shape[1], 1))) # model.add(Conv1D(filters=64, kernel_size=3, activation='relu')) # model.add(Dropout(0.5)) # model.add(MaxPooling1D(pool_size=2)) # model.add(Flatten()) # model.add(Dense(100, activation='relu')) # model.add(Dense(2, activation='relu')) '''2. MLP model''' n = 20 model.add( Dense(512, input_shape=(train_data_input.shape[1], ), activation='relu')) for i in range(n): model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(2, activation='relu')) # model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) optimizer = tf.keras.optimizers.RMSprop(0.001) model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse']) # fit network # history = model.fit(train_data_input,train_coordinates,epochs=EPOCHS,validation_split=0.2,verbose=1,callbacks=[PrintDot()]) # 使用early stop方法来fit network # early stop方法:如果经过一定数量的epochs后没有改进,则自动停止训练 # patience 值用来检查改进 epochs 的数量 early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10) history = model.fit(train_data_input, train_coordinates, epochs=EPOCHS, validation_split=0.2, verbose=1, callbacks=[early_stop, PrintDot()]) # 可视化训练进度 hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch hist.tail() plot_history(history) # 测试集测试 loss, mae, mse = model.evaluate(test_data_input, test_coordinates, verbose=2) print("Testing set Mean Abs Error: {:5.2f} ".format(mae)) # save the model model.save(CurrentModleFile)
def runMemory(xValueList, yValueList, date): """ test """ xTrain, xTest, yTrain, yTest = train_test_split(xValueList, yValueList, test_size=0.2, random_state=4) xTrain, xTest, yTrain, yTest = ( np.array(xTrain), np.array(xTest), np.array(yTrain), np.array(yTest), ) xTrain = np.reshape(xTrain, (xTrain.shape[0], xTrain.shape[1], len(memVariables) - 1)) # set last number to # of features model = Sequential() # Layer 1 model.add( LSTM( units=50, kernel_initializer="glorot_uniform", return_sequences=True, input_shape=(xTrain.shape[1], xTrain.shape[2]), )) model.add(Dropout(0.2)) # Layer 2 model.add( LSTM(units=50, kernel_initializer="glorot_uniform", return_sequences=True)) model.add(Dropout(0.2)) # Layer 3 model.add(LSTM(units=50, kernel_initializer="glorot_uniform")) model.add(Dropout(0.2)) model.add(Dense(yTrain.shape[1])) model.compile(loss=memLoss, optimizer=memOptimizer, metrics=['RootMeanSquaredError']) model.fit(xTrain, yTrain, epochs=memEpochs, batch_size=memBatchSize) #check predicted values #predictions = model.predict(xTest) #Undo scaling #unScaledPred = scaler.inverse_transform(predictions) accuracy = model.evaluate(xTest, yTest, batch_size=memBatchSize) return (model, accuracy)
def main(): DEBUG_MODE = True SAVE_DIR = "D:/tfData/" SAVE_FILE = SAVE_DIR + "kerasModel.hdf5" feature_num = 3 sequence_length = 20 train_batch_size = test_batch_size = 2 ** sequence_length // 10000 if DEBUG_MODE else 2 ** sequence_length // 3 all_possible = None if input("Generate datasets?(y/n): ") == 'y': all_possible = [f"{i:020b}" for i in range(2 ** sequence_length)] # Generate all 20-char long sequences of 0s and 1s shuffle(all_possible) print("all possibilities generated") # Input data dimensions : [batch size, sequence_length, input_dim] train_input_d = np.array([toList(i) for i in all_possible[:train_batch_size]]) # Take train_batch_size of that randomly as training data train_expected_d = [int(sum([sum(x) for x in y])) for y in train_input_d] train_expected_onehot_d = np.eye(sequence_length + 1)[train_expected_d] test_input_d = np.array([toList(i) for i in all_possible[train_batch_size:train_batch_size + test_batch_size]]) # Take test_batch_size of that again for the test set test_expected_d = [int(sum([sum(x) for x in y])) for y in test_input_d] test_expected_onehot_d = np.eye(sequence_length + 1)[test_expected_d] print("datasets organized") if input("Load the model?(y/n): ") == 'y': model = load_model(SAVE_FILE) # TODO: resolve "You are trying to load a weight file containing 2 layers into a model with 0 layers." else: model = Sequential([ GRU(16), Dropout(0.4), Dense(sequence_length + 1, input_shape=(feature_num,)), # (output size, input shape) Activation("relu"), ]) model.compile(optimizer="adagrad", loss="categorical_crossentropy", metrics=["accuracy"]) board = TensorBoard(log_dir=SAVE_DIR, write_graph=True) while True: print("Train the model(t), predict with it(p) or exit(e).") what = input("Choice: ") if what == 't': if all_possible is None: print("Datasets not generated") else: model.fit(train_input_d, train_expected_onehot_d, epochs=20, batch_size=train_batch_size, callbacks=[board]) print("eval accuracy: ") print(model.evaluate(test_input_d, test_expected_onehot_d)) model.save(SAVE_FILE) elif what == 'p': to_p = input("data: ") orig_data = np.array(toArray(to_p)) orig_ground = np.eye(sequence_length + 1)[sum([int(x) for x in to_p])] print(model.predict(orig_data, batch_size=1)) elif what == 'e': break
def train(model:Sequential, x_train, y_train, steps, epochs, x_test, y_test, model_name): model.compile( optimizer=SGD(lr=0.7, momentum=0.3), loss='mean_squared_error', metrics=['accuracy']) save_callback = ModelCheckpoint(filepath=model_name) early_stop = EarlyStopping(monitor='loss', min_delta=0.01, patience=20) model.fit(x=x_train, y=y_train, steps_per_epoch=steps, epochs=epochs, shuffle=True, callbacks=[save_callback, early_stop]) print(model.evaluate(x=x_test, y=y_test))
def recurrent_LSTM(train, label): X, Y = np.array(train), np.array(label) model = Sequential() #model.add(LSTM(32, input_shape=(1415684, 8), return_sequences=True)) model.add(LSTM(30, input_shape=(50, ))) #model.add(LSTM(64, input_dim=1, input_length=1415684, return_sequences=True)) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop') model.fit(train, label, batch_size=2000, nb_epoch=11) score = model.evaluate(train, label, batch_size=2000) return score
def copiedModel(): model = Sequential() #model.add(InputLayer(input_shape=(img_size_flat,))) #print("shape outputted by the Input layer: ",model.output_shape) model.add(Reshape(img_shape_full)) #print("shape outputted by the reshape layer: ",model.output_shape) model.add( Conv2D(filters=64, kernel_size=5, input_shape=img_shape_full, activation='relu', strides=(1, 1), padding='same', name='layer_conv1')) #print("shape outputted by the first convolutional layer: ",model.output_shape) model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) #print("shape outputted by the MaxPooling Layer layer: ",model.output_shape) model.add( Conv2D(filters=64, kernel_size=5, activation='relu', strides=(2, 2), padding='same', name='layer_conv2')) #print("shape outputted by the second Convolutional layer: ",model.output_shape) model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) #print("shape outputted by the second Maxpooling layer: ",model.output_shape) model.add(Conv2D(filters=128, kernel_size=4, activation='relu')) #print("shape outputted by the convolutional layer: ",model.output_shape) model.add(Dropout(rate=.3)) #print("shape outputted by the Dropout layer: ",model.output_shape) model.add(Flatten()) #print("shape outputted by the after flatten layer: ",model.output_shape) model.add(Dense(3072, activation='relu')) #print("shape outputted by the after Dense layer: ",model.output_shape) model.add(Dense(num_classes, activation='softmax')) optimizer = Adam(.001) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) model.fit(x=train_data, y=train_label, epochs=18, batch_size=50) result = model.evaluate(x=validation_data, y=validation_label) for name, value in zip(model.metrics_names, result): print('{0}: {1}'.format(name, value)) return model
def simpleModel(): #withh the following parameter accuracy found to be #acc_test = .446 #acc_train = .4464 model = Sequential() model.add(InputLayer(input_shape=(img_size_flat, ))) model.add(Reshape(img_shape_full)) model.add( Conv2D(filters=32, kernel_size=5, strides=(1, 1), activation='relu', padding='same', name='layer_conv1')) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add( Conv2D(filters=64, kernel_size=5, strides=(2, 2), activation='relu', padding='same', name='layer_conv2')) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add( Conv2D(filters=36, kernel_size=3, strides=(2, 2), activation='relu', padding='same', name='layer_conv3')) #model.add(MaxPooling2D(pool_size = (2,2),strides = (2,2))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(num_classes, activation='softmax')) optimizer = Adam(.001) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) model.fit(x=train_data, y=train_label, epochs=3, batch_size=64) result = model.evaluate(x=validation_data, y=validation_label) for name, value in zip(model.metrics_names, result): print('{0}: {1}'.format(name, value))
def train(): my_new_model = Sequential() my_new_model.add( ResNet50(include_top=False, pooling='avg', weights='imagenet')) my_new_model.add(Dense(num_classes, activation='softmax')) my_new_model.layers[0].trainable = False my_new_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) my_new_model.fit(X_train, y_train, epochs=2, batch_size=128) preds = my_new_model.evaluate(X_test, y_test, batch_size=10, verbose=1, sample_weight=None) my_new_model.summary() print("Loss = " + str(preds[0])) print("Test Accuracy = " + str(preds[1]))
def train_and_predict(X_train, X_test, Y_train, Y_test): max_words = 1226 tokenize = text.Tokenizer(num_words=max_words, char_level=False) tokenize.fit_on_texts(X_train) x_train = tokenize.texts_to_matrix(X_train) x_test = tokenize.texts_to_matrix(X_test) encoder = LabelEncoder() encoder.fit(Y_train) y_train = encoder.transform(Y_train) y_test = encoder.transform(Y_test) num_classes = np.max(y_train) + 1 y_train = utils.to_categorical(y_train, num_classes) y_test = utils.to_categorical(y_test, num_classes) batch_size = 32 epochs = 1000 # Build the model model = Sequential() model.add(Dense(512, input_shape=(max_words, ))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) tensorboard = TensorBoard(log_dir="logs/{}".format(time.time())) history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1, callbacks=[tensorboard]) score = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=1) print('Test accuracy:', score[1])
def run_resnet50(batch_size=16, epochs=20, lr=0.0001): resnet_weights_path = '/home/songyu/AICA/codes/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' image_size = 224 num_classes = 5 F = ld.Flower() flowers, Image, Label, Label_onehot = F.read_img(image_size) X_train, y_train, X_val, y_val, X_test, y_test = F.split_data(flowers, Image, Label, Label_onehot, returnwhat=2) X_train = np.vstack([X_train, X_val]) y_train = np.vstack([y_train, y_val]) model = Sequential() model.add( ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path)) model.add(Flatten()) model.add(BatchNormalization()) model.add(Dense(2048, activation='relu')) model.add(BatchNormalization()) model.add(Dense(1024, activation='relu')) model.add(BatchNormalization()) model.add(Dense(num_classes, activation='softmax')) model.layers[0].trainable = False model.compile(optimizer=tf.keras.optimizers.Adam(lr=lr), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.05) score = model.evaluate(X_test, y_test, batch_size=batch_size) print('test loss and accuracy is', score)
def train(model: Sequential, train_x, train_y, epoches, test_x, test_y, model_file): model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) print('running for %d epoches.' % epoches) save_model = ModelCheckpoint(model_file) stop_model = EarlyStopping(min_delta=0.001, patience=10) model.fit(x=train_x, y=train_y, shuffle=True, batch_size=60, epochs=epoches, validation_data=(test_x, test_y), callbacks=[save_model, stop_model]) print("Done training, Now evaluating.") loss, acc = model.evaluate(x=test_x, y=test_y) print("Final loss: %3.2f Final accuracy: %3.2f" % (loss, acc))
def build_nn_model(x_train, x_test, y_train, y_test): model = Sequential() model.add(Dense(input_shape=x_train[0].shape, units=13)) model.add(Dense(128, activation='relu')) model.add(Dropout(0.3)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(2, activation='softmax')) model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) print(model.summary()) model.fit(x_train, y_train, batch_size=32, epochs=1000, callbacks=[TensorBoard('./logs')]) model.save('./nn_model.h5') test_loss, test_acc = model.evaluate(x_test, y_test) print(test_acc)
def train(model: Sequential, epochs, train_x, train_y, test_x, test_y): model.compile(optimizer=RMSProp(), loss=losses.mean_squared_error, metrics=['accuracy']) print('running for %d epoches.' % epochs) save_model = ModelCheckpoint(MODEL_NAME) stop_model = EarlyStopping(min_delta=0.0002, patience=10) print("start training") model.fit(x=train_x, y=train_y, shuffle=True, batch_size=32, epochs=epochs, validation_data=(test_x, test_y), callbacks=[save_model, stop_model]) print("Done training, Now evaluating.") loss, acc = model.evaluate(x=test_x, y=test_y) print("Final loss: %3.2f Final accuracy: %3.2f" % (loss, acc))
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))
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
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()
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, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) assert score[1] > 0.95
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])