diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 7bf24ab4b..d11bdcd92 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -8,8 +8,8 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d - -Week 45: Decisions Trees, Random Forests, Bagging and Boosting + +Week 45, Recurrent Neural Networks @@ -36,109 +36,101 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d @@ -166,52 +158,46 @@ MathJax.Hub.Config({ - Week 45: Decisions Trees, Random Forests, Bagging and Boosting + Week 45, Recurrent Neural Networks +

Memoryless models

+

Autoregressive models Predict the next term in a sequence from a fixed number of previous terms using delay taps.

+ +
+
+ +

These generalize autoregressive +models by using one or more +layers of non-linear hidden units. +

+
+
+ + +

If we give our generative model some hidden state, and if we give +this hidden state its own internal dynamics, we get a much more +interesting kind of model. +

+
    +
  1. It can store information in its hidden state for a long time.
  2. +
  3. If the dynamics is noisy and the way it generates outputs from its hidden state is noisy, we can never know its exact hidden state.
  4. +
  5. The best we can do is to infer a probability distribution over the
  6. +
+

space of hidden state vectors.

+ +

This inference is only tractable for two types of hidden state model.

+

Linear dynamical model

+ +

If we give our generative model some hidden state, and if we give +this hidden state its own internal dynamics, we get a much more +interesting kind of model. +

+
    +
  1. It can store information in its hidden state for a long time. +
      +
    1. If the dynamics is noisy and the way it generates outputs from its hidden state is noisy, we can never know its exact hidden state.
    2. +
    +
  2. The best we can do is to infer a probability distribution over the space of hidden state vectors.
  3. +
+

Hidden Markov Models

+

Hidden Markov Models have a discrete oneof-\( N \) hidden state. Transitions between states +are stochastic and controlled by a transition +matrix. The outputs produced by a state are +stochastic. +

+ +

HMMs have efficient algorithms for inference and learning

+

RNNs

+ +

RNNs are very powerful, because they +combine two properties: +

+
    +
  1. Distributed hidden state that allows them to store a lot of information about the past efficiently.
  2. +
  3. Non-linear dynamics that allows them to update their hidden state in complicated ways.
  4. +
+

With enough neurons and time, RNNs +can compute anything that can be +computed by your computer. +

+

Do generative models need to be stochastic?

+ +
+
+ + +

But the posterior probability +distribution over their +hidden states given the +observed data so far is a +deterministic function of the +data. +

+
+
+ + +
+
+ +

Think of the hidden state +of an RNN as the +equivalent of the +deterministic probability +distribution over hidden +states in a linear dynamical +system or hidden Markov +model. +

+
+
+ +

What kinds of behaviour can RNNs exhibit?

+
    +
  1. They can oscillate.
  2. +
  3. They can settle to point attractors.
  4. +
  5. They can behave chaotically.
  6. +
  7. RNNs could potentially learn to implement lots of small programs that each capture a nugget of knowledge and run in parallel, interacting to produce very complicated effects.
  8. +
+

But the computational power of RNNs makes them very hard to train.

@@ -287,9 +423,6 @@ plt.show()

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • ...
  • -
  • 40
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs013.html b/doc/pub/week45/html/._week45-bs013.html index 7fd1bac56..7731c8f08 100644 --- a/doc/pub/week45/html/._week45-bs013.html +++ b/doc/pub/week45/html/._week45-bs013.html @@ -8,8 +8,8 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d - -Week 45: Decisions Trees, Random Forests, Bagging and Boosting + +Week 45, Recurrent Neural Networks @@ -36,109 +36,101 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d @@ -166,52 +158,46 @@ MathJax.Hub.Config({ - Week 45: Decisions Trees, Random Forests, Bagging and Boosting + Week 45, Recurrent Neural Networks diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index 7bf24ab4b..d11bdcd92 100644 --- a/doc/pub/week45/html/week45-bs.html +++ b/doc/pub/week45/html/week45-bs.html @@ -8,8 +8,8 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d - -Week 45: Decisions Trees, Random Forests, Bagging and Boosting + +Week 45, Recurrent Neural Networks @@ -36,109 +36,101 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d @@ -166,52 +158,46 @@ MathJax.Hub.Config({ - Week 45: Decisions Trees, Random Forests, Bagging and Boosting + Week 45, Recurrent Neural Networks +
    +
    +
    +
    +
    +
    +
    +
    + + +

    By default the grid search function includes cross validation with +five folds. The Scikit-Learn +documentation +contains more information on how to set the different parameters. +

    + +

    If we take out the random noise, running the above codes results in \( \lambda=0 \) yielding the best fit.

    + + +
    + + +

    An alternative to the above manual grid set up, is to use a random +search where the parameters are tuned from a random distribution +(uniform below) for a fixed number of iterations. A model is +constructed and evaluated for each combination of chosen parameters. +We repeat the previous example but now with a random search. Note +that values of \( \lambda \) are now limited to be within \( x\in +[0,1] \). This domain may not be the most relevant one for the specific +case under study. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import GridSearchCV
    +from scipy.stats import uniform as randuniform
    +from sklearn.model_selection import RandomizedSearchCV
    +
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(2021)
    +
    +n = 100
    +x = np.random.rand(n)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    +
    +Maxpolydegree = 5
    +X = np.zeros((n,Maxpolydegree-1))
    +
    +for degree in range(1,Maxpolydegree): #No intercept column
    +    X[:,degree-1] = x**(degree)
    +
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +param_grid = {'alpha': randuniform()}
    +# create and fit a ridge regression model, testing each alpha
    +model = Ridge()
    +gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
    +gridsearch.fit(X_train, y_train)
    +print(gridsearch)
    +ypredictRidge = gridsearch.predict(X_test)
    +# summarize the results of the grid search
    +print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    +print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    +print(f"R2 score: {R2(y_test,ypredictRidge)}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Wisconsin Cancer Data

    + +

    We show here how we can use a simple regression case on the breast +cancer data using Logistic regression as our algorithm for +classification. +

    + + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.linear_model import LogisticRegression
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Using the correlation matrix

    + +

    In addition to the above scores, we could also study the covariance (and the correlation matrix). +We use Pandas to compute the correlation matrix. +

    + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.linear_model import LogisticRegression
    +cancer = load_breast_cancer()
    +import pandas as pd
    +# Making a data frame
    +cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
    +
    +fig, axes = plt.subplots(15,2,figsize=(10,20))
    +malignant = cancer.data[cancer.target == 0]
    +benign = cancer.data[cancer.target == 1]
    +ax = axes.ravel()
    +
    +for i in range(30):
    +    _, bins = np.histogram(cancer.data[:,i], bins =50)
    +    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
    +    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
    +    ax[i].set_title(cancer.feature_names[i])
    +    ax[i].set_yticks(())
    +ax[0].set_xlabel("Feature magnitude")
    +ax[0].set_ylabel("Frequency")
    +ax[0].legend(["Malignant", "Benign"], loc ="best")
    +fig.tight_layout()
    +plt.show()
    +
    +import seaborn as sns
    +correlation_matrix = cancerpd.corr().round(1)
    +# use the heatmap function from seaborn to plot the correlation matrix
    +# annot = True to print the values inside the square
    +plt.figure(figsize=(15,8))
    +sns.heatmap(data=correlation_matrix, annot=True)
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Discussing the correlation data

    + +

    In the above example we note two things. In the first plot we display +the overlap of benign and malignant tumors as functions of the various +features in the Wisconsing breast cancer data set. We see that for +some of the features we can distinguish clearly the benign and +malignant cases while for other features we cannot. This can point to +us which features may be of greater interest when we wish to classify +a benign or not benign tumour. +

    + +

    In the second figure we have computed the so-called correlation +matrix, which in our case with thirty features becomes a \( 30\times 30 \) +matrix. +

    + +

    We constructed this matrix using pandas via the statements

    + + +
    +
    +
    +
    +
    +
    cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    and then

    + + +
    +
    +
    +
    +
    +
    correlation_matrix = cancerpd.corr().round(1)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Diagonalizing this matrix we can in turn say something about which +features are of relevance and which are not. This leads us to +the classical Principal Component Analysis (PCA) theorem with +applications. This will be discussed later this semester (week 43). +

    +
    + +
    +

    Other measures in classification studies: Cancer Data again

    + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.linear_model import LogisticRegression
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +#Cross validation
    +accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +
    +import scikitplot as skplt
    +y_pred = logreg.predict(X_test)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = logreg.predict_proba(X_test)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Material for Lecture Thursday November 9

    +
    + +
    +

    Recurrent neural networks (RNNs): Overarching view

    + +

    Till now our focus has been, including convolutional neural networks +as well, on feedforward neural networks. The output or the activations +flow only in one direction, from the input layer to the output layer. +

    + +

    A recurrent neural network (RNN) looks very much like a feedforward +neural network, except that it also has connections pointing +backward. +

    + +

    RNNs are used to analyze time series data such as stock prices, and +tell you when to buy or sell. In autonomous driving systems, they can +anticipate car trajectories and help avoid accidents. More generally, +they can work on sequences of arbitrary lengths, rather than on +fixed-sized inputs like all the nets we have discussed so far. For +example, they can take sentences, documents, or audio samples as +input, making them extremely useful for natural language processing +systems such as automatic translation and speech-to-text. +

    +
    + +
    +

    A simple example

    + + + +
    +
    +
    +
    +
    +
    # Start importing packages
     import pandas as pd
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn.tree import export_graphviz
    -from sklearn.preprocessing import StandardScaler, OneHotEncoder
    -from sklearn.compose import ColumnTransformer
    -from pydot import graph_from_dot_data
    -from sklearn.datasets import load_breast_cancer
    -from sklearn.svm import SVC
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.tree import DecisionTreeClassifier
    -from sklearn.ensemble import RandomForestClassifier
    -from sklearn.preprocessing import LabelEncoder
    -from sklearn.model_selection import cross_validate
    -import scikitplot as skplt
    -from sklearn.preprocessing import StandardScaler
    -import os
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -# Load the cancer data
    -cancer = load_breast_cancer()
    -
    -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    -print(X_train.shape)
    -print(X_test.shape)
    -#Scale the data
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -#define methods
    -# Logistic Regression
    -logreg = LogisticRegression(solver='lbfgs')
    -logreg.fit(X_train_scaled, y_train)
    -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    -# Decision Trees
    -deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    -deep_tree_clf.fit(X_train_scaled, y_train)
    -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
    -# Support Vector Machine
    -svm = SVC(gamma='auto', C=100)
    -svm.fit(X_train_scaled, y_train)
    -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    -# Random forests
    -#Instantiate the model with 500 trees and entropy as splitting criteria
    -Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
    -Random_Forest_model.fit(X_train_scaled, y_train)
    -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
    +import tensorflow as tf
    +from tensorflow.keras import datasets, layers, models
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Model, Sequential 
    +from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
    +from tensorflow.keras import optimizers     
    +from tensorflow.keras import regularizers           
    +from tensorflow.keras.utils import to_categorical 
     
     
     
    -y_pred = Random_Forest_model.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -plt.show()
    -y_probas = Random_Forest_model.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +# convert into dataset matrix
    +def convertToMatrix(data, step):
    + X, Y =[], []
    + for i in range(len(data)-step):
    +  d=i+step  
    +  X.append(data[i:d,])
    +  Y.append(data[d,])
    + return np.array(X), np.array(Y)
    +
    +step = 4
    +N = 1000    
    +Tp = 800    
    +
    +t=np.arange(0,N)
    +x=np.sin(0.02*t)+2*np.random.rand(N)
    +df = pd.DataFrame(x)
    +df.head()
    +
    +values=df.values
    +train,test = values[0:Tp,:], values[Tp:N,:]
    +
    +# add step elements into train and test
    +test = np.append(test,np.repeat(test[-1,],step))
    +train = np.append(train,np.repeat(train[-1,],step))
    + 
    +trainX,trainY =convertToMatrix(train,step)
    +testX,testY =convertToMatrix(test,step)
    +trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
    +testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
    +
    +model = Sequential()
    +model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
    +model.add(Dense(8, activation="relu")) 
    +model.add(Dense(1))
    +model.compile(loss='mean_squared_error', optimizer='rmsprop')
    +model.summary()
    +
    +model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
    +trainPredict = model.predict(trainX)
    +testPredict= model.predict(testX)
    +predicted=np.concatenate((trainPredict,testPredict),axis=0)
    +
    +trainScore = model.evaluate(trainX, trainY, verbose=0)
    +print(trainScore)
    +plt.plot(df)
    +plt.plot(predicted)
     plt.show()
     
    @@ -343,490 +843,389 @@ plt.show()
    -
    +

    Memoryless models

    -
    -

    Boosting, a Bird's Eye View

    +

    Autoregressive models Predict the next term in a sequence from a fixed number of previous terms using delay taps.

    -

    The basic idea is to combine weak classifiers in order to create a good -classifier. With a weak classifier we often intend a classifier which -produces results which are only slightly better than we would get by -random guesses. +

    +Feed-forward neural networks +

    +

    These generalize autoregressive +models by using one or more +layers of non-linear hidden units.

    +
    -

    This is done by applying in an iterative way a weak (or a standard -classifier like decision trees) to modify the data. In each iteration -we emphasize those observations which are misclassified by weighting -them with a factor. +

    If we give our generative model some hidden state, and if we give +this hidden state its own internal dynamics, we get a much more +interesting kind of model.

    -
    - -
    -

    What is boosting? Additive Modelling/Iterative Fitting

    - -

    Boosting is a way of fitting an additive expansion in a set of -elementary basis functions like for example some simple polynomials. -Assume for example that we have a function -

    -

     
    -$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ -

     
    - -

    where \( \beta_m \) are the expansion parameters to be determined in a -minimization process and \( b(x;\gamma_m) \) are some simple functions of -the multivariable parameter \( x \) which is characterized by the -parameters \( \gamma_m \). -

    - -

    As an example, consider the Sigmoid function we used in logistic -regression. In that case, we can translate the function -\( b(x;\gamma_m) \) into the Sigmoid function -

    - -

     
    -$$ -\sigma(t) = \frac{1}{1+\exp{(-t)}}, -$$ -

     
    - -

    where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and -\( \gamma_1 \) were determined by the Logistic Regression fitting -algorithm. -

    - -

    As another example, consider the cost function we defined for linear regression

    -

     
    -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ -

     
    - -

    In this case the function \( f(x) \) was replaced by the design matrix -\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), -that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can -simply invert a matrix and obtain the parameters \( \beta \) by -

    - -

     
    -$$ -\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ -

     
    - -

    In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).

    -
    - -
    -

    Iterative Fitting, Regression and Squared-error Cost Function

    - -

    The way we proceed is as follows (here we specialize to the squared-error cost function)

    -
      -

    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. -

    3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    4. -

    5. For \( m=1:M \) +

    6. It can store information in its hidden state for a long time.
    7. +

    8. If the dynamics is noisy and the way it generates outputs from its hidden state is noisy, we can never know its exact hidden state.
    9. +

    10. The best we can do is to infer a probability distribution over the
    11. +
    +

    +

    space of hidden state vectors.

    + +

    This inference is only tractable for two types of hidden state model.

    +

    Linear dynamical model

    + +

    If we give our generative model some hidden state, and if we give +this hidden state its own internal dynamics, we get a much more +interesting kind of model. +

    +
      +

    1. It can store information in its hidden state for a long time.
        -

      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. -

      3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      4. -

      5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      6. +

      7. If the dynamics is noisy and the way it generates outputs from its hidden state is noisy, we can never know its exact hidden state.

      +

    2. The best we can do is to infer a probability distribution over the space of hidden state vectors.

    -

    We could use any of the algorithms we have discussed till now. If we -use trees, \( \gamma \) parameterizes the split variables and split points -at the internal nodes, and the predictions at the terminal nodes. +

    Hidden Markov Models

    +

    Hidden Markov Models have a discrete oneof-\( N \) hidden state. Transitions between states +are stochastic and controlled by a transition +matrix. The outputs produced by a state are +stochastic.

    -
    + +

    +

    HMMs have efficient algorithms for inference and learning

    +

    RNNs

    -
    -

    Squared-Error Example and Iterative Fitting

    - -

    To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.

    - -

    For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \).

    - -

    This means that for every iteration \( m \), we need to optimize

    - -

     
    -$$ -(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. -$$ -

     
    - -

    We start our iteration by simply setting \( f_0(x)=0 \). -Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -

    -

     
    -$$ -\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, -$$ -

     
    - -

    and

    -

     
    -$$ -\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. -$$ -

     
    - -

    We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)

    -

     
    -$$ -\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, -$$ -

     
    - -

    which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have

    -

     
    -$$ -\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, -$$ -

     
    - -

    which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting -for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    - -

    The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as -\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). -

    -
    - -
    -

    Iterative Fitting, Classification and AdaBoost

    - -

    Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of -observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values -\( \{-1,1\} \). -

    - -

    The error rate of the training sample is then

    - -

     
    -$$ -\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). -$$ -

     
    - -

    The iterative procedure starts with defining a weak classifier whose -error rate is barely better than random guessing. The iterative -procedure in boosting is to sequentially apply a weak -classification algorithm to repeatedly modified versions of the data -producing a sequence of weak classifiers \( G_m(x) \). -

    - -

    Here we will express our function \( f(x) \) in terms of \( G(x) \). That is

    -

     
    -$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ -

     
    - -

    will be a function of

    -

     
    -$$ -G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). -$$ -

     
    -

    - -
    -

    Adaptive Boosting, AdaBoost

    - -

    In our iterative procedure we define thus

    -

     
    -$$ -f_m(x) = f_{m-1}(x)+\beta_mG_m(x). -$$ -

     
    - -

    The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the -exponential cost/loss function defined as -

    -

     
    -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. -$$ -

     
    - -

    We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. -This is normally done in two steps. Let us however first rewrite the cost function as -

    - -

     
    -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, -$$ -

     
    - -

    where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    -
    - -
    -

    Building up AdaBoost

    - -

    First, for any \( \beta > 0 \), we optimize \( G \) by setting

    -

     
    -$$ -G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), -$$ -

     
    - -

    which is the classifier that minimizes the weighted error rate in predicting \( y \).

    - -

    We can do this by rewriting

    -

     
    -$$ -\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, -$$ -

     
    - -

    which can be rewritten as

    -

     
    -$$ -(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, -$$ -

     
    - -

    which leads to

    -

     
    -$$ -\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, -$$ -

     
    - -

    where we have redefined the error as

    -

     
    -$$ -\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, -$$ -

     
    - -

    which leads to an update of

    -

     
    -$$ -f_m(x) = f_{m-1}(x) +\beta_m G_m(x). -$$ -

     
    - -

    This leads to the new weights

    -

     
    -$$ -w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} -$$ -

     
    -

    - -
    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    - -

    The algorithm here is rather straightforward. Assume that our weak -classifier is a decision tree and we consider a binary set of outputs -with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of -observations. Our design matrix is given in terms of the -feature/predictor vectors -\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a -classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    - -

    We have already defined the misclassification error \( \mathrm{err} \) as

    -

     
    -$$ -\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), -$$ -

     
    - -

    where the function \( I() \) is one if we misclassify and zero if we classify correctly.

    -
    - -
    -

    Basic Steps of AdaBoost

    - -

    With the above definitions we are now ready to set up the algorithm for AdaBoost. -The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. +

    RNNs are very powerful, because they +combine two properties:

      -

    1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. -

    3. We rewrite the misclassification error as
    4. +

    5. Distributed hidden state that allows them to store a lot of information about the past efficiently.
    6. +

    7. Non-linear dynamics that allows them to update their hidden state in complicated ways.

    -

     
    -$$ -\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, -$$ -

     
    +

    With enough neurons and time, RNNs +can compute anything that can be +computed by your computer. +

    +

    Do generative models need to be stochastic?

    + +
    +Linear dynamical systems and hidden Markov models are stochastic models. +

    + +

    But the posterior probability +distribution over their +hidden states given the +observed data so far is a +deterministic function of the +data. +

    +
    + + +
    +Recurrent neural networks are deterministic. +

    +

    Think of the hidden state +of an RNN as the +equivalent of the +deterministic probability +distribution over hidden +states in a linear dynamical +system or hidden Markov +model. +

    +
    +

    What kinds of behaviour can RNNs exhibit?

    +
      +

    1. They can oscillate.
    2. +

    3. They can settle to point attractors.
    4. +

    5. They can behave chaotically.
    6. +

    7. RNNs could potentially learn to implement lots of small programs that each capture a nugget of knowledge and run in parallel, interacting to produce very complicated effects.
    8. +
    +

    +

    But the computational power of RNNs makes them very hard to train.

    +
    + +
    +

    Basic layout

    + +

    +
    +

    +
    +

    +

    We need to specify the initial activity state of all the hidden and output units

      -

    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. +

    2. We could just fix these initial states to have some default value like 0.5.
    3. +

    4. But it is better to treat the initial states as learned parameters.
    5. +

    6. We learn them in the same way as we learn the weights.
    7. +

    8. Start off with an initial random guess for the initial states.
        -

      1. Fit then a given classifier to the training set using the weights \( w_i \).
      2. -

      3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
      4. -

      5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
      6. -

      7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
      8. +

      9. At the end of each training sequence, backpropagate through time all the way to the initial states to get the gradient of the error function with respect to each initial state.
      10. +

      11. Adjust the initial states by following the negative gradient.

      -

    9. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).

    -

    For the iterations with \( m \le 2 \) the weights are modified -individually at each steps. The observations which were misclassified -at iteration \( m-1 \) have a weight which is larger than those which were -classified properly. As this proceeds, the observations which were -difficult to classifiy correctly are given a larger influence. Each -new classification step \( m \) is then forced to concentrate on those -observations that are missed in the previous iterations. -

    -
    +

    We can specify inputs in several ways

    -
    -

    AdaBoost Examples

    - -

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

    - - - -
    -
    -
    -
    -
    -
    from sklearn.ensemble import AdaBoostClassifier
    -
    -ada_clf = AdaBoostClassifier(
    -    DecisionTreeClassifier(max_depth=2), n_estimators=200,
    -    algorithm="SAMME.R", learning_rate=0.01, random_state=42)
    -ada_clf.fit(X_train, y_train)
    -y_pred = ada_clf.predict(X_test)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -plt.show()
    -y_probas = ada_clf.predict_proba(X_test)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    - -

    Gradient boosting is again a similar technique to Adaptive boosting, -it combines so-called weak classifiers or regressors into a strong -method via a series of iterations. -

    - -

    In order to understand the method, let us illustrate its basics by -bringing back the essential steps in linear regression, where our cost -function was the least squares function. -

    -
    - -
    -

    The Squared-Error again! Steepest Descent

    - -

    We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize -This means that for every iteration, we need to optimize -

    - -

     
    -$$ -(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ -

     
    - -

    We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as

    -

     
    -$$ -f_M(x) = \sum_{m=0}^M h_m(x). -$$ -

     
    - -

    In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as

    -

     
    -$$ -g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. -$$ -

     
    - -

    With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that -the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). -

    - -

    Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have

    -

     
    -$$ -(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. -$$ -

     
    -

    - -
    -

    Steepest Descent Example

    - -

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that

    -

     
    -$$ -f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. -$$ -

     
    - -

    We can then proceed and compute

    -

     
    -$$ -g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, -$$ -

     
    - -

    and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting.

    -
    - -
    -

    Gradient Boosting, algorithm

    - -

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, -so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. -

    - -

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function

    -

     
    -$$ -C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ -

     
    - -

    The way we proceed in an iterative fashion is to

      -

    1. Initialize our estimate \( f_0(x) \).
    2. -

    3. For \( m=1:M \), we -
        -

      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. -

      3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      4. -

      5. update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
      6. +

      7. Specify the initial states of all the units.
      8. +

      9. Specify the initial states of a subset of the units.
      10. +

      11. Specify the states of the same subset of the units at every time step.

      -

    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    5. +

      This is the natural way to model most sequential data.

      +

      We can specify targets in several ways

      + +
        +

      1. Specify desired final activities of all the units
      2. +

      3. Specify desired activities of all units for the last few steps
      4. +

      5. Good for learning attractors
      6. +

      7. It is easy to add in extra error derivatives as we backpropagate.
      8. +
          + +

        • Specify the desired activity of a subset of the units.
        • +
        +

        +

      9. The other units are input or hidden units.
      +

      +

      +

      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      +

      Backpropagation through time

      + +
      + +

      +

      We can think of the recurrent net as a layered, feed-forward +net with shared weights and then train the feed-forward net +with weight constraints. +

      +
      + +

      We can also think of this training algorithm in the time domain:

      +
        +

      1. The forward pass builds up a stack of the activities of all the units at each time step.
      2. +

      3. The backward pass peels activities off the stack to compute the error derivatives at each time step.
      4. +

      5. After the backward pass we add together the derivatives at all the different times for each weight.
      6. +
      +

      +

      The backward pass is linear

      + +
        +

      1. There is a big difference between the forward and backward passes.
      2. +

      3. In the forward pass we use squashing functions (like the logistic) to prevent the activity vectors from exploding.
      4. +

      5. The backward pass, is completely linear. If you double the error derivatives at the final layer, all the error derivatives will double.
      6. +
      +

      +

      The forward pass determines the slope of the linear function used for +backpropagating through each neuron +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

    -

    Gradient Boosting, Examples of Regression

    +

    The problem of exploding or vanishing gradients

    + +

    +

    RNNs have difficulty dealing with long-range dependencies.

    +
    + +
    +

    Four effective ways to learn an RNN

    +
      +

    1. Long Short Term Memory Make the RNN out of little modules that are designed to remember values for a long time.
    2. +

    3. Hessian Free Optimization: Deal with the vanishing gradients problem by using a fancy optimizer that can detect directions with a tiny gradient but even smaller curvature.
    4. +

    5. Echo State Networks: Initialize the input a hidden and hidden-hidden and output-hidden connections very carefully so that the hidden state has a huge reservoir of weakly coupled oscillators which can be selectively driven by the input.
    6. + +

      +

    7. Good initialization with momentum Initialize like in Echo State Networks, but then learn all of the connections using momentum
    8. +
    +

    +

    Long Short Term Memory (LSTM)

    + +

    LSTM uses a memory cell for + modeling long-range dependencies and avoid vanishing gradient + problems. +

    + +
      +

    1. Introduced by Hochreiter and Schmidhuber (1997) who solved the problem of getting an RNN to remember things for a long time (like hundreds of time steps).
    2. +

    3. They designed a memory cell using logistic and linear units with multiplicative interactions.
    4. +

    5. Information gets into the cell whenever its “write” gate is on.
    6. +

    7. The information stays in the cell so long as its keep gate is on.
    8. +

    9. Information can be read from the cell by turning on its read gate.
    10. +
    +

    +

    Implementing a memory cell in a neural network

    +

    To preserve information for a long time in +the activities of an RNN, we use a circuit +that implements an analog memory cell. +

    + +
      +

    1. A linear unit that has a self-link with a weight of 1 will maintain its state.
    2. +

    3. Information is stored in the cell by activating its write gate.
    4. +

    5. Information is retrieved by activating the read gate.
    6. +

    7. We can backpropagate through this circuit because logistics are have nice derivatives.
    8. +
    +

    +

    +

    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    + +

    +
    +

    +
    +

    +
    + +
    +

    An extrapolation example

    + +

    The following code provides an example of how recurrent neural +networks can be used to extrapolate to unknown values of physics data +sets. Specifically, the data sets used in this program come from +a quantum mechanical many-body calculation of energies as functions of the number of particles. +

    +
    @@ -834,412 +1233,33 @@ $$
    -
    import matplotlib.pyplot as plt
    +  
    # For matrices and calculations
     import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.ensemble import GradientBoostingRegressor
    -import scikitplot as skplt
    -from sklearn.metrics import mean_squared_error
    -
    -n = 100
    -maxdegree = 6
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -for degree in range(1,maxdegree):
    -    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    -    model.fit(X_train,y_train)
    -    y_pred = model.predict(X_test)
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    -    variance[degree] = np.mean( np.var(y_pred) )
    -    print('Max depth:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.xlim(1,maxdegree-1)
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -save_fig("gdregression")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - -
    -

    Gradient Boosting, Classification Example

    - - -
    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import  train_test_split 
    -from sklearn.datasets import load_breast_cancer
    -import scikitplot as skplt
    -from sklearn.ensemble import GradientBoostingClassifier
    -from sklearn.model_selection import cross_validate
    -
    -# Load the data
    -cancer = load_breast_cancer()
    -
    -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    -print(X_train.shape)
    -print(X_test.shape)
    -#now scale the data
    -from sklearn.preprocessing import StandardScaler
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
    -gd_clf.fit(X_train_scaled, y_train)
    -#Cross validation
    -accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
    -print(accuracy)
    -print("Test set accuracy with Gradient boosting and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
    -
    -import scikitplot as skplt
    -y_pred = gd_clf.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -save_fig("gdclassiffierconfusion")
    -plt.show()
    -y_probas = gd_clf.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -save_fig("gdclassiffierroc")
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -save_fig("gdclassiffiercgain")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    XGBoost: Extreme Gradient Boosting

    - -

    XGBoost or Extreme Gradient -Boosting, is an optimized distributed gradient boosting library -designed to be highly efficient, flexible and portable. It implements -machine learning algorithms under the Gradient Boosting -framework. XGBoost provides a parallel tree boosting that solve many -data science problems in a fast and accurate way. See the article by Chen and Guestrin. -

    - -

    The authors design and build a highly scalable end-to-end tree -boosting system. It has a theoretically justified weighted quantile -sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. -

    - -

    It is now the algorithm which wins essentially all ML competitions!!!

    -
    - -
    -

    Regression Case

    - - - -
    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -import xgboost as xgb
    -import scikitplot as skplt
    -from sklearn.metrics import mean_squared_error
    -
    -n = 100
    -maxdegree = 6
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -for degree in range(maxdegree):
    -    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
    -
    -    model.fit(X_train,y_train)
    -    y_pred = model.predict(X_test)
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    -    variance[degree] = np.mean( np.var(y_pred) )
    -    print('Max depth:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.xlim(1,maxdegree-1)
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Xgboost on the Cancer Data

    - -

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.

    - - -
    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import  train_test_split 
    -from sklearn.datasets import load_breast_cancer
    -from sklearn.preprocessing import LabelEncoder
    -from sklearn.model_selection import cross_validate
    -import scikitplot as skplt
    -import xgboost as xgb
    -# Load the data
    -cancer = load_breast_cancer()
    -
    -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    -print(X_train.shape)
    -print(X_test.shape)
    -#now scale the data
    -from sklearn.preprocessing import StandardScaler
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -xg_clf = xgb.XGBClassifier()
    -xg_clf.fit(X_train_scaled,y_train)
    -
    -y_test = xg_clf.predict(X_test_scaled)
    -
    -print("Test set accuracy with Gradient Boosting and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
    -
    -import scikitplot as skplt
    -y_pred = xg_clf.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -save_fig("xdclassiffierconfusion")
    -plt.show()
    -y_probas = xg_clf.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -save_fig("xdclassiffierroc")
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -save_fig("gdclassiffiercgain")
    -plt.show()
    -
    -
    -xgb.plot_tree(xg_clf,num_trees=0)
    -plt.rcParams['figure.figsize'] = [50, 10]
    -save_fig("xgtree")
    -plt.show()
    -
    -xgb.plot_importance(xg_clf)
    -plt.rcParams['figure.figsize'] = [5, 5]
    -save_fig("xgparams")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Support Vector Machines, overarching aims

    - -

    A Support Vector Machine (SVM) is a very powerful and versatile -Machine Learning method, capable of performing linear or nonlinear -classification, regression, and even outlier detection. It is one of -the most popular models in Machine Learning, and anyone interested in -Machine Learning should have it in their toolbox. SVMs are -particularly well suited for classification of complex but small-sized or -medium-sized datasets. -

    - -

    The case with two well-separated classes only can be understood in an -intuitive way in terms of lines in a two-dimensional space separating -the two classes (see figure below). -

    - -

    The basic mathematics behind the SVM is however less familiar to most of us. -It relies on the definition of hyperplanes and the -definition of a margin which separates classes (in case of -classification problems) of variables. It is also used for regression -problems. -

    - -

    With SVMs we distinguish between hard margin and soft margins. The -latter introduces a so-called softening parameter to be discussed -below. We distinguish also between linear and non-linear -approaches. The latter are the most frequent ones since it is rather -unlikely that we can separate classes easily by say straight lines. -

    -
    - -
    -

    Hyperplanes and all that

    - -

    The theory behind support vector machines (SVM hereafter) is based on -the mathematical description of so-called hyperplanes. Let us start -with a two-dimensional case. This will also allow us to introduce our -first SVM examples. These will be tailored to the case of two specific -classes, as displayed in the figure here based on the usage of the petal data. -

    - -

    We assume here that our data set can be well separated into two -domains, where a straight line does the job in the separating the two -classes. Here the two classes are represented by either squares or -circles. -

    - - -
    -
    -
    -
    -
    -
    from sklearn import datasets
    -from sklearn.svm import SVC, LinearSVC
    -from sklearn.linear_model import SGDClassifier
    -from sklearn.preprocessing import StandardScaler
    -import matplotlib
    +# For machine learning (backend for keras)
    +import tensorflow as tf
    +# User-friendly machine learning library
    +# Front end for TensorFlow
    +import tensorflow.keras
    +# Different methods from Keras needed to create an RNN
    +# This is not necessary but it shortened function calls 
    +# that need to be used in the code.
    +from tensorflow.keras import datasets, layers, models
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras import regularizers
    +from tensorflow.keras.models import Model, Sequential
    +from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
    +# For timing the code
    +from timeit import default_timer as timer
    +# For plotting
     import matplotlib.pyplot as plt
    -plt.rcParams['axes.labelsize'] = 14
    -plt.rcParams['xtick.labelsize'] = 12
    -plt.rcParams['ytick.labelsize'] = 12
     
     
    -iris = datasets.load_iris()
    -X = iris["data"][:, (2, 3)]  # petal length, petal width
    -y = iris["target"]
    -
    -setosa_or_versicolor = (y == 0) | (y == 1)
    -X = X[setosa_or_versicolor]
    -y = y[setosa_or_versicolor]
    -
    -
    -
    -C = 5
    -alpha = 1 / (C * len(X))
    -
    -lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
    -svm_clf = SVC(kernel="linear", C=C)
    -sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
    -                        max_iter=100000, random_state=42)
    -
    -scaler = StandardScaler()
    -X_scaled = scaler.fit_transform(X)
    -
    -lin_clf.fit(X_scaled, y)
    -svm_clf.fit(X_scaled, y)
    -sgd_clf.fit(X_scaled, y)
    -
    -print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
    -print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
    -print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
    -
    -# Compute the slope and bias of each decision boundary
    -w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
    -b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
    -w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
    -b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
    -w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
    -b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
    -
    -# Transform the decision boundary lines back to the original scale
    -line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
    -line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
    -line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
    -
    -# Plot all three decision boundaries
    -plt.figure(figsize=(11, 4))
    -plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
    -plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
    -plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
    -plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
    -plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
    -plt.xlabel("Petal length", fontsize=14)
    -plt.ylabel("Petal width", fontsize=14)
    -plt.legend(loc="upper center", fontsize=14)
    -plt.axis([0, 5.5, 0, 2])
    -
    -plt.show()
    +# The data set
    +datatype='VaryDimension'
    +X_tot = np.arange(2, 42, 2)
    +y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
    +	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
    +	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
     
    @@ -1257,194 +1277,43 @@ plt.show()
    -

    What is a hyperplane?

    +

    Formatting the Data

    -

    The aim of the SVM algorithm is to find a hyperplane in a -\( p \)-dimensional space, where \( p \) is the number of features that -distinctly classifies the data points. +

    The way the recurrent neural networks are trained in this program +differs from how machine learning algorithms are usually trained. +Typically a machine learning algorithm is trained by learning the +relationship between the x data and the y data. In this program, the +recurrent neural network will be trained to recognize the relationship +in a sequence of y values. This is type of data formatting is +typically used time series forcasting, but it can also be used in any +extrapolation (time series forecasting is just a specific type of +extrapolation along the time axis). This method of data formatting +does not use the x data and assumes that the y data are evenly spaced.

    -

    In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). -As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is -a two-dimensional subspace, or stated simply, a plane. +

    For a standard machine learning algorithm, the training data has the +form of (x,y) so the machine learning algorithm learns to assiciate a +y value with a given x value. This is useful when the test data has x +values within the same range as the training data. However, for this +application, the x values of the test data are outside of the x values +of the training data and the traditional method of training a machine +learning algorithm does not work as well. For this reason, the +recurrent neural network is trained on sequences of y values of the +form ((y1, y2), y3), so that the network is concerned with learning +the pattern of the y data and not the relation between the x and y +data. As long as the pattern of y data outside of the training region +stays relatively stable compared to what was inside the training +region, this method of training can produce accurate extrapolations to +y values far removed from the training data set.

    -

    In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as

    -

     
    -$$ -b+w_1x_1+w_2x_2=0, -$$ -

     
    + + + + + + -

    where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line -\( b+w_1x_1+w_2x_2=0 \). -In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). -We can then rewrite the above equation as -

    - -

     
    -$$ -\boldsymbol{x}^T\boldsymbol{w}+b=0. -$$ -

     
    -

    - -
    -

    A \( p \)-dimensional space of features

    - -

    We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). -In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as -

    -

     
    -$$ -b+wx_1+w_2x_2+\dots +w_px_p=0. -$$ -

     
    - -

    If we define a -matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) -of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), -

    -

     
    -$$ -\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. -$$ -

     
    - -

    If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have

    -

     
    -$$ -b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, -$$ -

     
    - -

    if our output \( y_i=1 \). -In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if -

    -

     
    -$$ -b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, -$$ -

     
    - -

    for the class of observations \( y_i=-1 \), -then \( \boldsymbol{x}_i \) lies on the other side. -

    - -

    Equivalently, for the two classes of observations we have

    -

     
    -$$ -y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. -$$ -

     
    - -

    When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.

    -
    - -
    -

    The two-dimensional case

    - -

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional -plane. To separate the two classes of data points, there are many -possible lines (hyperplanes if you prefer a more strict naming) -that could be chosen. Our objective is to find a -plane that has the maximum margin, i.e the maximum distance between -data points of both classes. Maximizing the margin distance provides -some reinforcement so that future data points can be classified with -more confidence. -

    - -

    What a linear classifier attempts to accomplish is to split the -feature space into two half spaces by placing a hyperplane between the -data points. This hyperplane will be our decision boundary. All -points on one side of the plane will belong to class one and all points -on the other side of the plane will belong to the second class two. -

    - -

    Unfortunately there are many ways in which we can place a hyperplane -to divide the data. Below is an example of two candidate hyperplanes -for our data sample. -

    -
    - -
    -

    Getting into the details

    - -

    Let us define the function

    -

     
    -$$ -f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, -$$ -

     
    - -

    as the function that determines the line \( L \) that separates two classes (our two features), see the figure here.

    - -

    Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \).

    - -

    The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then

    -

     
    -$$ -\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). -$$ -

     
    -

    - -
    -

    First attempt at a minimization approach

    - -

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could -do is to define a cost function which now contains the set of all -misclassified points \( M \) and attempt to minimize this function -

    - -

     
    -$$ -C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). -$$ -

     
    - -

    We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us

    -

     
    -$$ -\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, -$$ -

     
    - -

    and

    -

     
    -$$ -\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. -$$ -

     
    -

    - -
    -

    Solving the equations

    - -

    We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations

    -

     
    -$$ -b \leftarrow b +\eta \frac{\partial C}{\partial b}, -$$ -

     
    - -

    and

    -

     
    -$$ -\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, -$$ -

     
    - -

    where \( \eta \) is our by now well-known learning rate.

    -
    - -
    -

    Code Example

    - -

    The equations we discussed above can be coded rather easily (the -framework is similar to what we developed for logistic -regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. -

    @@ -1452,7 +1321,78 @@ regression). We are going to set up a simple case with two classes only and we w
    -
    +  
    # FORMAT_DATA
    +def format_data(data, length_of_sequence = 2):  
    +    """
    +        Inputs:
    +            data(a numpy array): the data that will be the inputs to the recurrent neural
    +                network
    +            length_of_sequence (an int): the number of elements in one iteration of the
    +                sequence patter.  For a function approximator use length_of_sequence = 2.
    +        Returns:
    +            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
    +                dimensions are length of data - length of sequence, length of sequence, 
    +                dimnsion of data
    +            rnn_output (a numpy array): the training data for the neural network
    +        Formats data to be used in a recurrent neural network.
    +    """
    +
    +    X, Y = [], []
    +    for i in range(len(data)-length_of_sequence):
    +        # Get the next length_of_sequence elements
    +        a = data[i:i+length_of_sequence]
    +        # Get the element that immediately follows that
    +        b = data[i+length_of_sequence]
    +        # Reshape so that each data point is contained in its own array
    +        a = np.reshape (a, (len(a), 1))
    +        X.append(a)
    +        Y.append(b)
    +    rnn_input = np.array(X)
    +    rnn_output = np.array(Y)
    +
    +    return rnn_input, rnn_output
    +
    +
    +# ## Defining the Recurrent Neural Network Using Keras
    +# 
    +# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.
    +
    +def rnn(length_of_sequences, batch_size = None, stateful = False):
    +    """
    +        Inputs:
    +            length_of_sequences (an int): the number of y values in "x data".  This is determined
    +                when the data is formatted
    +            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
    +            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
    +        Returns:
    +            model (a Keras model): The recurrent neural network that is built and compiled by this
    +                method
    +        Builds and compiles a recurrent neural network with one hidden layer and returns the model.
    +    """
    +    # Number of neurons in the input and output layers
    +    in_out_neurons = 1
    +    # Number of neurons in the hidden layer
    +    hidden_neurons = 200
    +    # Define the input layer
    +    inp = Input(batch_shape=(batch_size, 
    +                length_of_sequences, 
    +                in_out_neurons))  
    +    # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to 
    +    # the network immediately after the input layer
    +    rnn = SimpleRNN(hidden_neurons, 
    +                    return_sequences=False,
    +                    stateful = stateful,
    +                    name="RNN")(inp)
    +    # Define the output layer as a dense neural network layer (standard neural network layer)
    +    #and add it to the network immediately after the hidden layer.
    +    dens = Dense(in_out_neurons,name="dense")(rnn)
    +    # Create the machine learning model starting with the input layer and ending with the 
    +    # output layer
    +    model = Model(inputs=[inp],outputs=[dens])
    +    # Compile the machine learning model using the mean squared error function as the loss 
    +    # function and an Adams optimizer.
    +    model.compile(loss="mean_squared_error", optimizer="adam")  
    +    return model
     
    @@ -1470,410 +1410,477 @@ regression). We are going to set up a simple case with two classes only and we w
    -

    Problems with the Simpler Approach

    +

    Predicting New Points With A Trained Recurrent Neural Network

    -

    There are however problems with this approach, although it looks -pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. -

    -

    For small -gaps between the entries, we may also end up needing many iterations -before the solutions converge and if the data cannot be separated -properly into two distinct classes, we may not experience a converge -at all. -

    + +
    +
    +
    +
    +
    +
    def test_rnn (x1, y_test, plot_min, plot_max):
    +    """
    +        Inputs:
    +            x1 (a list or numpy array): The complete x component of the data set
    +            y_test (a list or numpy array): The complete y component of the data set
    +            plot_min (an int or float): the smallest x value used in the training data
    +            plot_max (an int or float): the largest x valye used in the training data
    +        Returns:
    +            None.
    +        Uses a trained recurrent neural network model to predict future points in the 
    +        series.  Computes the MSE of the predicted data set from the true data set, saves
    +        the predicted data set to a csv file, and plots the predicted and true data sets w
    +        while also displaying the data range used for training.
    +    """
    +    # Add the training data as the first dim points in the predicted data array as these
    +    # are known values.
    +    y_pred = y_test[:dim].tolist()
    +    # Generate the first input to the trained recurrent neural network using the last two 
    +    # points of the training data.  Based on how the network was trained this means that it
    +    # will predict the first point in the data set after the training data.  All of the 
    +    # brackets are necessary for Tensorflow.
    +    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
    +    # Save the very last point in the training data set.  This will be used later.
    +    last = [y_test[dim-1]]
    +
    +    # Iterate until the complete data set is created.
    +    for i in range (dim, len(y_test)):
    +        # Predict the next point in the data set using the previous two points.
    +        next = model.predict(next_input)
    +        # Append just the number of the predicted data set
    +        y_pred.append(next[0][0])
    +        # Create the input that will be used to predict the next data point in the data set.
    +        next_input = np.array([[last, next[0]]], dtype=np.float64)
    +        last = next
    +
    +    # Print the mean squared error between the known data set and the predicted data set.
    +    print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())
    +    # Save the predicted data set as a csv file for later use
    +    name = datatype + 'Predicted'+str(dim)+'.csv'
    +    np.savetxt(name, y_pred, delimiter=',')
    +    # Plot the known data set and the predicted data set.  The red box represents the region that was used
    +    # for the training data.
    +    fig, ax = plt.subplots()
    +    ax.plot(x1, y_test, label="true", linewidth=3)
    +    ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4)
    +    ax.legend()
    +    # Created a red region to represent the points used in the training data.
    +    ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')
    +    plt.show()
    +
    +# Check to make sure the data set is complete
    +assert len(X_tot) == len(y_tot)
    +
    +# This is the number of points that will be used in as the training data
    +dim=12
    +
    +# Separate the training data from the whole data set
    +X_train = X_tot[:dim]
    +y_train = y_tot[:dim]
    +
    +
    +# Generate the training data for the RNN, using a sequence of 2
    +rnn_input, rnn_training = format_data(y_train, 2)
    +
    +
    +# Create a recurrent neural network in Keras and produce a summary of the 
    +# machine learning model
    +model = rnn(length_of_sequences = rnn_input.shape[1])
    +model.summary()
    +
    +# Start the timer.  Want to time training+testing
    +start = timer()
    +# Fit the model using the training data genenerated above using 150 training iterations and a 5%
    +# validation split.  Setting verbose to True prints information about each training iteration.
    +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
    +                 verbose=True,validation_split=0.05)
    +
    +for label in ["loss","val_loss"]:
    +    plt.plot(hist.history[label],label=label)
    +
    +plt.ylabel("loss")
    +plt.xlabel("epoch")
    +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
    +plt.legend()
    +plt.show()
    +
    +# Use the trained neural network to predict more points of the data set
    +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
    +# Stop the timer and calculate the total time needed.
    +end = timer()
    +print('Time: ', end-start)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    A better approach

    +

    Other Things to Try

    -

    A better approach is rather to try to define a large margin between -the two classes (if they are well separated from the beginning). +

    Changing the size of the recurrent neural network and its parameters +can drastically change the results you get from the model. The below +code takes the simple recurrent neural network from above and adds a +second hidden layer, changes the number of neurons in the hidden +layer, and explicitly declares the activation function of the hidden +layers to be a sigmoid function. The loss function and optimizer can +also be changed but are kept the same as the above network. These +parameters can be tuned to provide the optimal result from the +network. For some ideas on how to improve the performance of a +recurrent neural network.

    -

    Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to -\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition -

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. -$$ -

     
    + +

    +
    +
    +
    +
    +
    def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
    +    """
    +        Inputs:
    +            length_of_sequences (an int): the number of y values in "x data".  This is determined
    +                when the data is formatted
    +            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
    +            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
    +        Returns:
    +            model (a Keras model): The recurrent neural network that is built and compiled by this
    +                method
    +        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
    +    """
    +    # Number of neurons in the input and output layers
    +    in_out_neurons = 1
    +    # Number of neurons in the hidden layer, increased from the first network
    +    hidden_neurons = 500
    +    # Define the input layer
    +    inp = Input(batch_shape=(batch_size, 
    +                length_of_sequences, 
    +                in_out_neurons))  
    +    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
    +    # function to be the sigmoid function (the default value is hyperbolic tangent)
    +    rnn1 = SimpleRNN(hidden_neurons, 
    +                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
    +                    stateful = stateful, activation = 'sigmoid',
    +                    name="RNN1")(inp)
    +    rnn2 = SimpleRNN(hidden_neurons, 
    +                    return_sequences=False, activation = 'sigmoid',
    +                    stateful = stateful,
    +                    name="RNN2")(rnn1)
    +    # Define the output layer as a dense neural network layer (standard neural network layer)
    +    #and add it to the network immediately after the hidden layer.
    +    dens = Dense(in_out_neurons,name="dense")(rnn2)
    +    # Create the machine learning model starting with the input layer and ending with the 
    +    # output layer
    +    model = Model(inputs=[inp],outputs=[dens])
    +    # Compile the machine learning model using the mean squared error function as the loss 
    +    # function and an Adams optimizer.
    +    model.compile(loss="mean_squared_error", optimizer="adam")  
    +    return model
     
    -

    All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line.

    +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) -

    We seek thus the largest value \( M \) defined by

    -

     
    -$$ -\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, -$$ -

     
    +# This is the number of points that will be used in as the training data +dim=12 -

    or just

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. -$$ -

     
    +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] -

    If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of -\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition -

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. -$$ -

     
    -

    We have thus defined our margin as the invers of the norm of -\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as -possible margin \( M \). Before we proceed, we need to remind ourselves -about Lagrangian multipliers. -

    +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +model = rnn_2layers(length_of_sequences = 2) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    A quick Reminder on Lagrangian Multipliers

    +

    Other Types of Recurrent Neural Networks

    -

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an -extreme we have -

    -

     
    -$$ -df=0. -$$ -

     
    - -

    A necessary and sufficient condition is

    -

     
    -$$ -\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, -$$ -

     
    - -

    due to

    -

     
    -$$ -df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. -$$ -

     
    - -

    In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) -so that they are no longer all independent. It is possible at least in principle to use each -constraint to eliminate one variable -and to proceed with a new and smaller set of independent varables. +

    Besides a simple recurrent neural network layer, there are two other +commonly used types of recurrent neural network layers: Long Short +Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short +introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b +and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b.

    -

    The use of so-called Lagrangian multipliers is an alternative technique when the elimination -of variables is incovenient or undesirable. Assume that we have an equation of constraint on -the variables \( x,y,z \) -

    -

     
    -$$ -\phi(x,y,z) = 0, -$$ -

     
    - -

    resulting in

    -

     
    -$$ -d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. -$$ -

     
    - -

    Now we cannot set anymore

    -

     
    -$$ -\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, -$$ -

     
    - -

    if \( df=0 \) is wanted -because there are now only two independent variables! Assume \( x \) and \( y \) are the independent -variables. -Then \( dz \) is no longer arbitrary. -

    -
    - -
    -

    Adding the Multiplier

    - -

    However, we can add to

    -

     
    -$$ -df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, -$$ -

     
    - -

    a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in

    -

     
    -$$ -df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda -\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ -(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. -$$ -

     
    - -

    Our multiplier is chosen so that

    -

     
    -$$ -\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. -$$ -

     
    - -

    We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have

    -

     
    -$$ -\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, -$$ -

     
    - -

    and

    -

     
    -$$ -\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. -$$ -

     
    - -

    When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and -\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, -it is therefore often called -Lagrange's undetermined multiplier. -If we have a set of constraints \( \phi_k \) we have the equations -

    -

     
    -$$ -\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. -$$ -

     
    -

    - -
    -

    Setting up the Problem

    -

    In order to solve the above problem, we define the following Lagrangian function to be minimized

    -

     
    -$$ -{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], -$$ -

     
    - -

    where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).

    - -

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    -

     
    -$$ -\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, -$$ -

     
    - -

    and

    -

     
    -$$ -\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. -$$ -

     
    - -

    Inserting these constraints into the equation for \( {\cal L} \) we obtain

    -

     
    -$$ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, -$$ -

     
    - -

    subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). -We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition -

    -

     
    -$$ -\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. -$$ -

     
    - -

      -

    1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
    2. -

    3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
    4. -
    -

    -

    When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \).

    -
    - -
    -

    The problem to solve

    - -

    We can rewrite

    -

     
    -$$ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, -$$ -

     
    - -

    and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem

    -

     
    -$$ -\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ -y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ -\dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots \\ -y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ -\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, -$$ -

     
    - -

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and -\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). -

    -
    - -
    -

    The last steps

    - -

    Solving the above problem, yields the values of \( \lambda_i \). -To find the coefficients of your hyperplane we need simply to compute -

    -

     
    -$$ -\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. -$$ -

     
    - -

    With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, -$$ -

     
    - -

    resulting in

    -

     
    -$$ -b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, -$$ -

     
    - -

    or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have

    -

     
    -$$ -b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). -$$ -

     
    - -

    With our hyperplane coefficients we can use our classifier to assign any observation by simply using

    -

     
    -$$ -y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). -$$ -

     
    - -

    Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier.

    -
    - -
    -

    A soft classifier

    - -

    Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.

    - -

    Suppose now that classes overlap in feature space, as shown in the -figure here. One way to deal with this problem before we define the -so-called kernel approach, is to allow a kind of slack in the sense -that we allow some points to be on the wrong side of the margin. +

    The first network created below is similar to the previous network, +but it replaces the SimpleRNN layers with LSTM layers. The second +network below has two hidden layers made up of GRUs, which are +preceeded by two dense (feeddorward) neural network layers. These +dense layers "preprocess" the data before it reaches the recurrent +layers. This architecture has been shown to improve the performance +of recurrent neural networks (see the link above and also +https://arxiv.org/pdf/1807.02857.pdf.

    -

    We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and -modify our previous equation -

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, -$$ -

     
    -

    to

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, -$$ -

     
    + +

    +
    +
    +
    +
    +
    def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
    +    """
    +        Inputs:
    +            length_of_sequences (an int): the number of y values in "x data".  This is determined
    +                when the data is formatted
    +            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
    +            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
    +        Returns:
    +            model (a Keras model): The recurrent neural network that is built and compiled by this
    +                method
    +        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
    +    """
    +    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
    +    in_out_neurons = 1
    +    hidden_neurons = 250
    +    # Input Layer
    +    inp = Input(batch_shape=(batch_size, 
    +                length_of_sequences, 
    +                in_out_neurons)) 
    +    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
    +    rnn= LSTM(hidden_neurons, 
    +                    return_sequences=True,
    +                    stateful = stateful,
    +                    name="RNN", use_bias=True, activation='tanh')(inp)
    +    rnn1 = LSTM(hidden_neurons, 
    +                    return_sequences=False,
    +                    stateful = stateful,
    +                    name="RNN1", use_bias=True, activation='tanh')(rnn)
    +    # Output layer
    +    dens = Dense(in_out_neurons,name="dense")(rnn1)
    +    # Define the midel
    +    model = Model(inputs=[inp],outputs=[dens])
    +    # Compile the model
    +    model.compile(loss='mean_squared_error', optimizer='adam')  
    +    # Return the model
    +    return model
     
    -

    with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). -The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction -\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), -we bound the total amount by which predictions fall on the wrong side of their margins. -

    +def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with four hidden layers (two dense followed by + two GRU layers) and returns the model. + """ + # Number of neurons on the input/output layers and hidden layers + in_out_neurons = 1 + hidden_neurons = 250 + # Input layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Hidden Dense (feedforward) layers + dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp) + dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn) + # Hidden GRU layers + rnn1 = GRU(hidden_neurons, + return_sequences=True, + stateful = stateful, + name="RNN1", use_bias=True)(dnn1) + rnn = GRU(hidden_neurons, + return_sequences=False, + stateful = stateful, + name="RNN", use_bias=True)(rnn1) + # Output layer + dens = Dense(in_out_neurons,name="dense")(rnn) + # Define the model + model = Model(inputs=[inp],outputs=[dens]) + # Compile the mdoel + model.compile(loss='mean_squared_error', optimizer='adam') + # Return the model + return model -

    Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of -misclassifications. -

    -
    +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) -
    -

    Soft optmization problem

    +# This is the number of points that will be used in as the training data +dim=12 -

    This has in turn the consequences that we change our optmization problem to finding the minimum of

    -

     
    -$$ -{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, -$$ -

     
    +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] -

    subject to

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, -$$ -

     
    -

    with the requirement \( \xi_i\geq 0 \).

    +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) -

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    -

     
    -$$ -\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, -$$ -

     
    -

    and

    -

     
    -$$ -\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, -$$ -

     
    +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +# Change the method name to reflect which network you want to use +model = dnn2_gru2(length_of_sequences = 2) +model.summary() -

    and

    -

     
    -$$ -\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. -$$ -

     
    +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) -

    Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before

    -

     
    -$$ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, -$$ -

     
    -

    but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). -We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads -

    -

     
    -$$ -\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, -$$ -

     
    +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) -

     
    -$$ -\gamma_i\xi_i = 0, -$$ -

     
    +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() -

    and

    -

     
    -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. -$$ -

     
    +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) + + +# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data) +# +# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation. + +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + +# Reshape the data for Keras specifications +X_train = X_train.reshape((dim, 1)) +y_train = y_train.reshape((dim, 1)) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +# Set the sequence length to 1 for regular data formatting +model = rnn(length_of_sequences = 1) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(X_train, y_train, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict the remaining data points +X_pred = X_tot[dim:] +X_pred = X_pred.reshape((len(X_pred), 1)) +y_model = model.predict(X_pred) +y_pred = np.concatenate((y_tot[:dim], y_model.flatten())) + +# Plot the known data set and the predicted data set. The red box represents the region that was used +# for the training data. +fig, ax = plt.subplots() +ax.plot(X_tot, y_tot, label="true", linewidth=3) +ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4) +ax.legend() +# Created a red region to represent the points used in the training data. +ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red') +plt.show() + +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) + + + + + +

    +
    +
    +
    +
    +
    +
    +
    +
    diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html index bf203837b..b9aa6f339 100644 --- a/doc/pub/week45/html/week45-solarized.html +++ b/doc/pub/week45/html/week45-solarized.html @@ -8,8 +8,8 @@ doconce format html week45.do.txt --pygments_html_style=perldoc --html_style=sol - -Week 45: Decisions Trees, Random Forests, Bagging and Boosting + +Week 45, Recurrent Neural Networks @@ -63,109 +63,101 @@ div.toc p,a { @@ -187,7 +179,7 @@ MathJax.Hub.Config({
    -

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    +

    Week 45, Recurrent Neural Networks

    @@ -203,46 +195,137 @@ MathJax.Hub.Config({
    -

    Nov 11, 2022

    +

    November 6-10












    -

    Overview of week 45

    +

    Plan for week 45

    -
    -Videos +Material for the active learning sessions on Tuesday and Wednesday

    -

      -
    1. Video on Decision trees
    2. -
    3. Video on boosting methods by Hastie.
    4. -
    5. Video on AdaBoost
    6. -
    7. Video on Gradient boost, part 1, parts 2-4 follows
    8. -
    +
    - +
    -Reading +Material for the lecture on Thursday November 9, 2023

    -

      -
    1. Hastie et al, chapter 10.1-10.10. Geron's chapters 6 and 7 are also useful.
    2. -
    +










    -

    Brief code reminder from last wekk

    +

    Material for the lab sessions, additional ways to present classification results and other practicalities

    + +









    +

    Searching for Optimal Regularization Parameters \( \lambda \)

    + +

    In project 1, when using Ridge and Lasso regression, we end up +searching for the optimal parameter \( \lambda \) which minimizes our +selected scores (MSE or \( R2 \) values for example). The brute force +approach, as discussed in the code here for Ridge regression, consists +in evaluating the MSE as function of different \( \lambda \) values. +Based on these calculations, one tries then to determine the value of the hyperparameter \( \lambda \) +which results in optimal scores (for example the smallest MSE or an \( R2=1 \)). +

    + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from sklearn.model_selection import train_test_split
    +from sklearn import linear_model
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(2021)
    +
    +n = 100
    +x = np.random.rand(n)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    +
    +Maxpolydegree = 5
    +X = np.zeros((n,Maxpolydegree-1))
    +
    +for degree in range(1,Maxpolydegree): #No intercept column
    +    X[:,degree-1] = x**(degree)
    +
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +# Decide which values of lambda to use
    +nlambdas = 500
    +MSERidgePredict = np.zeros(nlambdas)
    +lambdas = np.logspace(-4, 2, nlambdas)
    +for i in range(nlambdas):
    +    lmb = lambdas[i]
    +    RegRidge = linear_model.Ridge(lmb)
    +    RegRidge.fit(X_train,y_train)
    +    ypredictRidge = RegRidge.predict(X_test)
    +    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    +
    +# Now plot the results
    +plt.figure()
    +plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('MSE')
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we have performed a rather data greedy calculation as function of the regularization parameter \( \lambda \). There is no resampling here. The latter can easily be added by employing the function RidgeCV instead of just calling the Ridge function. For RidgeCV we need to pass the array of \( \lambda \) values. +By inspecting the figure we can in turn determine which is the optimal regularization parameter. +This becomes however less functional in the long run. +

    + +









    + + +

    An alternative is to use the so-called grid search functionality +included with the library Scikit-Learn, as demonstrated for the same +example here. +

    @@ -251,91 +334,485 @@ MathJax.Hub.Config({
    -
    %matplotlib inline
    -# Common imports
    -from IPython.display import Image 
    -from pydot import graph_from_dot_data
    +  
    import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import GridSearchCV
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(2021)
    +
    +n = 100
    +x = np.random.rand(n)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    +
    +Maxpolydegree = 5
    +X = np.zeros((n,Maxpolydegree-1))
    +
    +for degree in range(1,Maxpolydegree): #No intercept column
    +    X[:,degree-1] = x**(degree)
    +
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +# Decide which values of lambda to use
    +nlambdas = 10
    +lambdas = np.logspace(-4, 2, nlambdas)
    +# create and fit a ridge regression model, testing each alpha
    +model = Ridge()
    +gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))
    +gridsearch.fit(X_train, y_train)
    +print(gridsearch)
    +ypredictRidge = gridsearch.predict(X_test)
    +# summarize the results of the grid search
    +print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    +print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    +print(f"R2 score: {R2(y_test,ypredictRidge)}")
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    By default the grid search function includes cross validation with +five folds. The Scikit-Learn +documentation +contains more information on how to set the different parameters. +

    + +

    If we take out the random noise, running the above codes results in \( \lambda=0 \) yielding the best fit.

    + +









    + + +

    An alternative to the above manual grid set up, is to use a random +search where the parameters are tuned from a random distribution +(uniform below) for a fixed number of iterations. A model is +constructed and evaluated for each combination of chosen parameters. +We repeat the previous example but now with a random search. Note +that values of \( \lambda \) are now limited to be within \( x\in +[0,1] \). This domain may not be the most relevant one for the specific +case under study. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import GridSearchCV
    +from scipy.stats import uniform as randuniform
    +from sklearn.model_selection import RandomizedSearchCV
    +
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(2021)
    +
    +n = 100
    +x = np.random.rand(n)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    +
    +Maxpolydegree = 5
    +X = np.zeros((n,Maxpolydegree-1))
    +
    +for degree in range(1,Maxpolydegree): #No intercept column
    +    X[:,degree-1] = x**(degree)
    +
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +param_grid = {'alpha': randuniform()}
    +# create and fit a ridge regression model, testing each alpha
    +model = Ridge()
    +gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
    +gridsearch.fit(X_train, y_train)
    +print(gridsearch)
    +ypredictRidge = gridsearch.predict(X_test)
    +# summarize the results of the grid search
    +print(f"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}")
    +print(f"MSE score: {MSE(y_test,ypredictRidge)}")
    +print(f"R2 score: {R2(y_test,ypredictRidge)}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Wisconsin Cancer Data

    + +

    We show here how we can use a simple regression case on the breast +cancer data using Logistic regression as our algorithm for +classification. +

    + + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.linear_model import LogisticRegression
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Using the correlation matrix

    + +

    In addition to the above scores, we could also study the covariance (and the correlation matrix). +We use Pandas to compute the correlation matrix. +

    + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.linear_model import LogisticRegression
    +cancer = load_breast_cancer()
    +import pandas as pd
    +# Making a data frame
    +cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
    +
    +fig, axes = plt.subplots(15,2,figsize=(10,20))
    +malignant = cancer.data[cancer.target == 0]
    +benign = cancer.data[cancer.target == 1]
    +ax = axes.ravel()
    +
    +for i in range(30):
    +    _, bins = np.histogram(cancer.data[:,i], bins =50)
    +    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
    +    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
    +    ax[i].set_title(cancer.feature_names[i])
    +    ax[i].set_yticks(())
    +ax[0].set_xlabel("Feature magnitude")
    +ax[0].set_ylabel("Frequency")
    +ax[0].legend(["Malignant", "Benign"], loc ="best")
    +fig.tight_layout()
    +plt.show()
    +
    +import seaborn as sns
    +correlation_matrix = cancerpd.corr().round(1)
    +# use the heatmap function from seaborn to plot the correlation matrix
    +# annot = True to print the values inside the square
    +plt.figure(figsize=(15,8))
    +sns.heatmap(data=correlation_matrix, annot=True)
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Discussing the correlation data

    + +

    In the above example we note two things. In the first plot we display +the overlap of benign and malignant tumors as functions of the various +features in the Wisconsing breast cancer data set. We see that for +some of the features we can distinguish clearly the benign and +malignant cases while for other features we cannot. This can point to +us which features may be of greater interest when we wish to classify +a benign or not benign tumour. +

    + +

    In the second figure we have computed the so-called correlation +matrix, which in our case with thirty features becomes a \( 30\times 30 \) +matrix. +

    + +

    We constructed this matrix using pandas via the statements

    + + +
    +
    +
    +
    +
    +
    cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    and then

    + + +
    +
    +
    +
    +
    +
    correlation_matrix = cancerpd.corr().round(1)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Diagonalizing this matrix we can in turn say something about which +features are of relevance and which are not. This leads us to +the classical Principal Component Analysis (PCA) theorem with +applications. This will be discussed later this semester (week 43). +

    + +









    +

    Other measures in classification studies: Cancer Data again

    + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.linear_model import LogisticRegression
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +#Cross validation
    +accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +
    +import scikitplot as skplt
    +y_pred = logreg.predict(X_test)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = logreg.predict_proba(X_test)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Material for Lecture Thursday November 9

    + +









    +

    Recurrent neural networks (RNNs): Overarching view

    + +

    Till now our focus has been, including convolutional neural networks +as well, on feedforward neural networks. The output or the activations +flow only in one direction, from the input layer to the output layer. +

    + +

    A recurrent neural network (RNN) looks very much like a feedforward +neural network, except that it also has connections pointing +backward. +

    + +

    RNNs are used to analyze time series data such as stock prices, and +tell you when to buy or sell. In autonomous driving systems, they can +anticipate car trajectories and help avoid accidents. More generally, +they can work on sequences of arbitrary lengths, rather than on +fixed-sized inputs like all the nets we have discussed so far. For +example, they can take sentences, documents, or audio samples as +input, making them extremely useful for natural language processing +systems such as automatic translation and speech-to-text. +

    + +









    +

    A simple example

    + + + +
    +
    +
    +
    +
    +
    # Start importing packages
     import pandas as pd
     import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn.tree import export_graphviz
    -from sklearn.preprocessing import StandardScaler, OneHotEncoder
    -from sklearn.compose import ColumnTransformer
    -from pydot import graph_from_dot_data
    -from sklearn.datasets import load_breast_cancer
    -from sklearn.svm import SVC
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.tree import DecisionTreeClassifier
    -from sklearn.ensemble import RandomForestClassifier
    -from sklearn.preprocessing import LabelEncoder
    -from sklearn.model_selection import cross_validate
    -import scikitplot as skplt
    -from sklearn.preprocessing import StandardScaler
    -import os
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -# Load the cancer data
    -cancer = load_breast_cancer()
    -
    -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    -print(X_train.shape)
    -print(X_test.shape)
    -#Scale the data
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -#define methods
    -# Logistic Regression
    -logreg = LogisticRegression(solver='lbfgs')
    -logreg.fit(X_train_scaled, y_train)
    -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    -# Decision Trees
    -deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    -deep_tree_clf.fit(X_train_scaled, y_train)
    -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
    -# Support Vector Machine
    -svm = SVC(gamma='auto', C=100)
    -svm.fit(X_train_scaled, y_train)
    -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    -# Random forests
    -#Instantiate the model with 500 trees and entropy as splitting criteria
    -Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
    -Random_Forest_model.fit(X_train_scaled, y_train)
    -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
    +import tensorflow as tf
    +from tensorflow.keras import datasets, layers, models
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Model, Sequential 
    +from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
    +from tensorflow.keras import optimizers     
    +from tensorflow.keras import regularizers           
    +from tensorflow.keras.utils import to_categorical 
     
     
     
    -y_pred = Random_Forest_model.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -plt.show()
    -y_probas = Random_Forest_model.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +# convert into dataset matrix
    +def convertToMatrix(data, step):
    + X, Y =[], []
    + for i in range(len(data)-step):
    +  d=i+step  
    +  X.append(data[i:d,])
    +  Y.append(data[d,])
    + return np.array(X), np.array(Y)
    +
    +step = 4
    +N = 1000    
    +Tp = 800    
    +
    +t=np.arange(0,N)
    +x=np.sin(0.02*t)+2*np.random.rand(N)
    +df = pd.DataFrame(x)
    +df.head()
    +
    +values=df.values
    +train,test = values[0:Tp,:], values[Tp:N,:]
    +
    +# add step elements into train and test
    +test = np.append(test,np.repeat(test[-1,],step))
    +train = np.append(train,np.repeat(train[-1,],step))
    + 
    +trainX,trainY =convertToMatrix(train,step)
    +testX,testY =convertToMatrix(test,step)
    +trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
    +testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
    +
    +model = Sequential()
    +model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
    +model.add(Dense(8, activation="relu")) 
    +model.add(Dense(1))
    +model.compile(loss='mean_squared_error', optimizer='rmsprop')
    +model.summary()
    +
    +model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
    +trainPredict = model.predict(trainX)
    +testPredict= model.predict(testX)
    +predicted=np.concatenate((trainPredict,testPredict),axis=0)
    +
    +trainScore = model.evaluate(trainX, trainY, verbose=0)
    +print(trainScore)
    +plt.plot(df)
    +plt.plot(predicted)
     plt.show()
     
    @@ -351,1004 +828,400 @@ plt.show()
    +

    Memoryless models

    +

    Autoregressive models Predict the next term in a sequence from a fixed number of previous terms using delay taps.

    -









    -

    Boosting, a Bird's Eye View

    - -

    The basic idea is to combine weak classifiers in order to create a good -classifier. With a weak classifier we often intend a classifier which -produces results which are only slightly better than we would get by -random guesses. +

    +Feed-forward neural networks +

    +

    These generalize autoregressive +models by using one or more +layers of non-linear hidden units.

    +
    -

    This is done by applying in an iterative way a weak (or a standard -classifier like decision trees) to modify the data. In each iteration -we emphasize those observations which are misclassified by weighting -them with a factor. + +

    If we give our generative model some hidden state, and if we give +this hidden state its own internal dynamics, we get a much more +interesting kind of model.

    - -









    -

    What is boosting? Additive Modelling/Iterative Fitting

    - -

    Boosting is a way of fitting an additive expansion in a set of -elementary basis functions like for example some simple polynomials. -Assume for example that we have a function -

    -$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ - -

    where \( \beta_m \) are the expansion parameters to be determined in a -minimization process and \( b(x;\gamma_m) \) are some simple functions of -the multivariable parameter \( x \) which is characterized by the -parameters \( \gamma_m \). -

    - -

    As an example, consider the Sigmoid function we used in logistic -regression. In that case, we can translate the function -\( b(x;\gamma_m) \) into the Sigmoid function -

    - -$$ -\sigma(t) = \frac{1}{1+\exp{(-t)}}, -$$ - -

    where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and -\( \gamma_1 \) were determined by the Logistic Regression fitting -algorithm. -

    - -

    As another example, consider the cost function we defined for linear regression

    -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ - -

    In this case the function \( f(x) \) was replaced by the design matrix -\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), -that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can -simply invert a matrix and obtain the parameters \( \beta \) by -

    - -$$ -\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. -$$ - -

    In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).

    - -









    -

    Iterative Fitting, Regression and Squared-error Cost Function

    - -

    The way we proceed is as follows (here we specialize to the squared-error cost function)

    -
      -
    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. -
    3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    4. -
    5. For \( m=1:M \) +
    6. It can store information in its hidden state for a long time.
    7. +
    8. If the dynamics is noisy and the way it generates outputs from its hidden state is noisy, we can never know its exact hidden state.
    9. +
    10. The best we can do is to infer a probability distribution over the
    11. +
    +

    space of hidden state vectors.

    + +

    This inference is only tractable for two types of hidden state model.

    +

    Linear dynamical model

    + +

    If we give our generative model some hidden state, and if we give +this hidden state its own internal dynamics, we get a much more +interesting kind of model. +

    +
      +
    1. It can store information in its hidden state for a long time.
        -
      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. -
      3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      4. -
      5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      6. +
      7. If the dynamics is noisy and the way it generates outputs from its hidden state is noisy, we can never know its exact hidden state.
      +
    2. The best we can do is to infer a probability distribution over the space of hidden state vectors.
    -

    We could use any of the algorithms we have discussed till now. If we -use trees, \( \gamma \) parameterizes the split variables and split points -at the internal nodes, and the predictions at the terminal nodes. +

    Hidden Markov Models

    +

    Hidden Markov Models have a discrete oneof-\( N \) hidden state. Transitions between states +are stochastic and controlled by a transition +matrix. The outputs produced by a state are +stochastic.

    + +

    HMMs have efficient algorithms for inference and learning

    +

    RNNs

    -









    -

    Squared-Error Example and Iterative Fitting

    - -

    To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.

    - -

    For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \).

    - -

    This means that for every iteration \( m \), we need to optimize

    - -$$ -(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. -$$ - -

    We start our iteration by simply setting \( f_0(x)=0 \). -Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -

    -$$ -\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, -$$ - -

    and

    -$$ -\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. -$$ - -

    We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)

    -$$ -\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, -$$ - -

    which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have

    -$$ -\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, -$$ - -

    which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting -for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    - -

    The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as -\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). -

    - -









    -

    Iterative Fitting, Classification and AdaBoost

    - -

    Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of -observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values -\( \{-1,1\} \). -

    - -

    The error rate of the training sample is then

    - -$$ -\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). -$$ - -

    The iterative procedure starts with defining a weak classifier whose -error rate is barely better than random guessing. The iterative -procedure in boosting is to sequentially apply a weak -classification algorithm to repeatedly modified versions of the data -producing a sequence of weak classifiers \( G_m(x) \). -

    - -

    Here we will express our function \( f(x) \) in terms of \( G(x) \). That is

    -$$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), -$$ - -

    will be a function of

    -$$ -G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). -$$ - - -









    -

    Adaptive Boosting, AdaBoost

    - -

    In our iterative procedure we define thus

    -$$ -f_m(x) = f_{m-1}(x)+\beta_mG_m(x). -$$ - -

    The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the -exponential cost/loss function defined as -

    -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. -$$ - -

    We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. -This is normally done in two steps. Let us however first rewrite the cost function as -

    - -$$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, -$$ - -

    where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    - -









    -

    Building up AdaBoost

    - -

    First, for any \( \beta > 0 \), we optimize \( G \) by setting

    -$$ -G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), -$$ - -

    which is the classifier that minimizes the weighted error rate in predicting \( y \).

    - -

    We can do this by rewriting

    -$$ -\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, -$$ - -

    which can be rewritten as

    -$$ -(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, -$$ - -

    which leads to

    -$$ -\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, -$$ - -

    where we have redefined the error as

    -$$ -\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, -$$ - -

    which leads to an update of

    -$$ -f_m(x) = f_{m-1}(x) +\beta_m G_m(x). -$$ - -

    This leads to the new weights

    -$$ -w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} -$$ - - -









    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    - -

    The algorithm here is rather straightforward. Assume that our weak -classifier is a decision tree and we consider a binary set of outputs -with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of -observations. Our design matrix is given in terms of the -feature/predictor vectors -\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a -classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    - -

    We have already defined the misclassification error \( \mathrm{err} \) as

    -$$ -\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), -$$ - -

    where the function \( I() \) is one if we misclassify and zero if we classify correctly.

    - -









    -

    Basic Steps of AdaBoost

    - -

    With the above definitions we are now ready to set up the algorithm for AdaBoost. -The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. +

    RNNs are very powerful, because they +combine two properties:

      -
    1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. -
    3. We rewrite the misclassification error as
    4. +
    5. Distributed hidden state that allows them to store a lot of information about the past efficiently.
    6. +
    7. Non-linear dynamics that allows them to update their hidden state in complicated ways.
    -$$ -\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, -$$ +

    With enough neurons and time, RNNs +can compute anything that can be +computed by your computer. +

    +

    Do generative models need to be stochastic?

    + +
    +Linear dynamical systems and hidden Markov models are stochastic models. +

    + +

    But the posterior probability +distribution over their +hidden states given the +observed data so far is a +deterministic function of the +data. +

    +
    + + +
    +Recurrent neural networks are deterministic. +

    +

    Think of the hidden state +of an RNN as the +equivalent of the +deterministic probability +distribution over hidden +states in a linear dynamical +system or hidden Markov +model. +

    +
    + +

    What kinds of behaviour can RNNs exhibit?

    +
      +
    1. They can oscillate.
    2. +
    3. They can settle to point attractors.
    4. +
    5. They can behave chaotically.
    6. +
    7. RNNs could potentially learn to implement lots of small programs that each capture a nugget of knowledge and run in parallel, interacting to produce very complicated effects.
    8. +
    +

    But the computational power of RNNs makes them very hard to train.

    + +









    +

    Basic layout

    + +

    +
    +

    +
    +

    +

    We need to specify the initial activity state of all the hidden and output units

      -
    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. +
    2. We could just fix these initial states to have some default value like 0.5.
    3. +
    4. But it is better to treat the initial states as learned parameters.
    5. +
    6. We learn them in the same way as we learn the weights.
    7. +
    8. Start off with an initial random guess for the initial states.
        -
      1. Fit then a given classifier to the training set using the weights \( w_i \).
      2. -
      3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
      4. -
      5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
      6. -
      7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
      8. +
      9. At the end of each training sequence, backpropagate through time all the way to the initial states to get the gradient of the error function with respect to each initial state.
      10. +
      11. Adjust the initial states by following the negative gradient.
      -
    9. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
    -

    For the iterations with \( m \le 2 \) the weights are modified -individually at each steps. The observations which were misclassified -at iteration \( m-1 \) have a weight which is larger than those which were -classified properly. As this proceeds, the observations which were -difficult to classifiy correctly are given a larger influence. Each -new classification step \( m \) is then forced to concentrate on those -observations that are missed in the previous iterations. -

    +

    We can specify inputs in several ways

    -









    -

    AdaBoost Examples

    - -

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

    - - - -
    -
    -
    -
    -
    -
    from sklearn.ensemble import AdaBoostClassifier
    -
    -ada_clf = AdaBoostClassifier(
    -    DecisionTreeClassifier(max_depth=2), n_estimators=200,
    -    algorithm="SAMME.R", learning_rate=0.01, random_state=42)
    -ada_clf.fit(X_train, y_train)
    -y_pred = ada_clf.predict(X_test)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -plt.show()
    -y_probas = ada_clf.predict_proba(X_test)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    - -

    Gradient boosting is again a similar technique to Adaptive boosting, -it combines so-called weak classifiers or regressors into a strong -method via a series of iterations. -

    - -

    In order to understand the method, let us illustrate its basics by -bringing back the essential steps in linear regression, where our cost -function was the least squares function. -

    - -









    -

    The Squared-Error again! Steepest Descent

    - -

    We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize -This means that for every iteration, we need to optimize -

    - -$$ -(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ - -

    We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as

    -$$ -f_M(x) = \sum_{m=0}^M h_m(x). -$$ - -

    In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as

    -$$ -g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. -$$ - -

    With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that -the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). -

    - -

    Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have

    -$$ -(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. -$$ - - -









    -

    Steepest Descent Example

    - -

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that

    -$$ -f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. -$$ - -

    We can then proceed and compute

    -$$ -g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, -$$ - -

    and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting.

    - -









    -

    Gradient Boosting, algorithm

    - -

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, -so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. -

    - -

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function

    -$$ -C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ - -

    The way we proceed in an iterative fashion is to

      -
    1. Initialize our estimate \( f_0(x) \).
    2. -
    3. For \( m=1:M \), we -
        -
      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. -
      3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      4. -
      5. update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
      6. +
      7. Specify the initial states of all the units.
      8. +
      9. Specify the initial states of a subset of the units.
      10. +
      11. Specify the states of the same subset of the units at every time step.
      -
    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    5. +

      This is the natural way to model most sequential data.

      +

      We can specify targets in several ways

      + +
        +
      1. Specify desired final activities of all the units
      2. +
      3. Specify desired activities of all units for the last few steps
      4. +
      5. Good for learning attractors
      6. +
      7. It is easy to add in extra error derivatives as we backpropagate.
      8. +
          +
        • Specify the desired activity of a subset of the units.
        • +
        +
      9. The other units are input or hidden units.
      -









      -

      Gradient Boosting, Examples of Regression

      +

      +
      +

      +
      +

      - -
      -
      -
      -
      -
      -
      import matplotlib.pyplot as plt
      -import numpy as np
      -from sklearn.model_selection import train_test_split
      -from sklearn.ensemble import GradientBoostingRegressor
      -import scikitplot as skplt
      -from sklearn.metrics import mean_squared_error
      +

      +
      +

      +
      +

      -n = 100 -maxdegree = 6 +

      +
      +

      +
      +

      -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +

      +
      +

      +
      +

      +

      Backpropagation through time

      -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(1,maxdegree): - model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) - model.fit(X_train,y_train) - y_pred = model.predict(X_test) - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) - variance[degree] = np.mean( np.var(y_pred) ) - print('Max depth:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.xlim(1,maxdegree-1) -plt.plot(polydegree, error, label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -save_fig("gdregression") -plt.show() -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      +
      + +

      +

      We can think of the recurrent net as a layered, feed-forward +net with shared weights and then train the feed-forward net +with weight constraints. +

      -









      -

      Gradient Boosting, Classification Example

      +

      We can also think of this training algorithm in the time domain:

      +
        +
      1. The forward pass builds up a stack of the activities of all the units at each time step.
      2. +
      3. The backward pass peels activities off the stack to compute the error derivatives at each time step.
      4. +
      5. After the backward pass we add together the derivatives at all the different times for each weight.
      6. +
      +

      The backward pass is linear

      - -
      -
      -
      -
      -
      -
      import matplotlib.pyplot as plt
      -import numpy as np
      -from sklearn.model_selection import  train_test_split 
      -from sklearn.datasets import load_breast_cancer
      -import scikitplot as skplt
      -from sklearn.ensemble import GradientBoostingClassifier
      -from sklearn.model_selection import cross_validate
      -
      -# Load the data
      -cancer = load_breast_cancer()
      -
      -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
      -print(X_train.shape)
      -print(X_test.shape)
      -#now scale the data
      -from sklearn.preprocessing import StandardScaler
      -scaler = StandardScaler()
      -scaler.fit(X_train)
      -X_train_scaled = scaler.transform(X_train)
      -X_test_scaled = scaler.transform(X_test)
      -
      -gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
      -gd_clf.fit(X_train_scaled, y_train)
      -#Cross validation
      -accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
      -print(accuracy)
      -print("Test set accuracy with Gradient boosting and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
      -
      -import scikitplot as skplt
      -y_pred = gd_clf.predict(X_test_scaled)
      -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
      -save_fig("gdclassiffierconfusion")
      -plt.show()
      -y_probas = gd_clf.predict_proba(X_test_scaled)
      -skplt.metrics.plot_roc(y_test, y_probas)
      -save_fig("gdclassiffierroc")
      -plt.show()
      -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
      -save_fig("gdclassiffiercgain")
      -plt.show()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - - -









      -

      XGBoost: Extreme Gradient Boosting

      - -

      XGBoost or Extreme Gradient -Boosting, is an optimized distributed gradient boosting library -designed to be highly efficient, flexible and portable. It implements -machine learning algorithms under the Gradient Boosting -framework. XGBoost provides a parallel tree boosting that solve many -data science problems in a fast and accurate way. See the article by Chen and Guestrin. +

        +
      1. There is a big difference between the forward and backward passes.
      2. +
      3. In the forward pass we use squashing functions (like the logistic) to prevent the activity vectors from exploding.
      4. +
      5. The backward pass, is completely linear. If you double the error derivatives at the final layer, all the error derivatives will double.
      6. +
      +

      The forward pass determines the slope of the linear function used for +backpropagating through each neuron

      -

      The authors design and build a highly scalable end-to-end tree -boosting system. It has a theoretically justified weighted quantile -sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. -

      +

      +
      +

      +
      +

      -

      It is now the algorithm which wins essentially all ML competitions!!!

      +

      +
      +

      +
      +

      -









      -

      Regression Case

      +

      +
      +

      +
      +

      +

      +
      +

      +
      +

      - -
      -
      -
      -
      -
      -
      import matplotlib.pyplot as plt
      -import numpy as np
      -from sklearn.model_selection import train_test_split
      -import xgboost as xgb
      -import scikitplot as skplt
      -from sklearn.metrics import mean_squared_error
      +

      +
      +

      +
      +

      -n = 100 -maxdegree = 6 +

      +
      +

      +
      +

      -# Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) - -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) -X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -for degree in range(maxdegree): - model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200) - - model.fit(X_train,y_train) - y_pred = model.predict(X_test) - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) - variance[degree] = np.mean( np.var(y_pred) ) - print('Max depth:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.xlim(1,maxdegree-1) -plt.plot(polydegree, error, label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - - -









      -

      Xgboost on the Cancer Data

      - -

      As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.

      - - -
      -
      -
      -
      -
      -
      import matplotlib.pyplot as plt
      -import numpy as np
      -from sklearn.model_selection import  train_test_split 
      -from sklearn.datasets import load_breast_cancer
      -from sklearn.preprocessing import LabelEncoder
      -from sklearn.model_selection import cross_validate
      -import scikitplot as skplt
      -import xgboost as xgb
      -# Load the data
      -cancer = load_breast_cancer()
      -
      -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
      -print(X_train.shape)
      -print(X_test.shape)
      -#now scale the data
      -from sklearn.preprocessing import StandardScaler
      -scaler = StandardScaler()
      -scaler.fit(X_train)
      -X_train_scaled = scaler.transform(X_train)
      -X_test_scaled = scaler.transform(X_test)
      -
      -xg_clf = xgb.XGBClassifier()
      -xg_clf.fit(X_train_scaled,y_train)
      -
      -y_test = xg_clf.predict(X_test_scaled)
      -
      -print("Test set accuracy with Gradient Boosting and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
      -
      -import scikitplot as skplt
      -y_pred = xg_clf.predict(X_test_scaled)
      -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
      -save_fig("xdclassiffierconfusion")
      -plt.show()
      -y_probas = xg_clf.predict_proba(X_test_scaled)
      -skplt.metrics.plot_roc(y_test, y_probas)
      -save_fig("xdclassiffierroc")
      -plt.show()
      -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
      -save_fig("gdclassiffiercgain")
      -plt.show()
      -
      -
      -xgb.plot_tree(xg_clf,num_trees=0)
      -plt.rcParams['figure.figsize'] = [50, 10]
      -save_fig("xgtree")
      -plt.show()
      -
      -xgb.plot_importance(xg_clf)
      -plt.rcParams['figure.figsize'] = [5, 5]
      -save_fig("xgparams")
      -plt.show()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - - -









      -

      Support Vector Machines, overarching aims

      - -

      A Support Vector Machine (SVM) is a very powerful and versatile -Machine Learning method, capable of performing linear or nonlinear -classification, regression, and even outlier detection. It is one of -the most popular models in Machine Learning, and anyone interested in -Machine Learning should have it in their toolbox. SVMs are -particularly well suited for classification of complex but small-sized or -medium-sized datasets. -

      - -

      The case with two well-separated classes only can be understood in an -intuitive way in terms of lines in a two-dimensional space separating -the two classes (see figure below). -

      - -

      The basic mathematics behind the SVM is however less familiar to most of us. -It relies on the definition of hyperplanes and the -definition of a margin which separates classes (in case of -classification problems) of variables. It is also used for regression -problems. -

      - -

      With SVMs we distinguish between hard margin and soft margins. The -latter introduces a so-called softening parameter to be discussed -below. We distinguish also between linear and non-linear -approaches. The latter are the most frequent ones since it is rather -unlikely that we can separate classes easily by say straight lines. -

      - -









      -

      Hyperplanes and all that

      - -

      The theory behind support vector machines (SVM hereafter) is based on -the mathematical description of so-called hyperplanes. Let us start -with a two-dimensional case. This will also allow us to introduce our -first SVM examples. These will be tailored to the case of two specific -classes, as displayed in the figure here based on the usage of the petal data. -

      - -

      We assume here that our data set can be well separated into two -domains, where a straight line does the job in the separating the two -classes. Here the two classes are represented by either squares or -circles. -

      - - -
      -
      -
      -
      -
      -
      from sklearn import datasets
      -from sklearn.svm import SVC, LinearSVC
      -from sklearn.linear_model import SGDClassifier
      -from sklearn.preprocessing import StandardScaler
      -import matplotlib
      -import matplotlib.pyplot as plt
      -plt.rcParams['axes.labelsize'] = 14
      -plt.rcParams['xtick.labelsize'] = 12
      -plt.rcParams['ytick.labelsize'] = 12
      -
      -
      -iris = datasets.load_iris()
      -X = iris["data"][:, (2, 3)]  # petal length, petal width
      -y = iris["target"]
      -
      -setosa_or_versicolor = (y == 0) | (y == 1)
      -X = X[setosa_or_versicolor]
      -y = y[setosa_or_versicolor]
      -
      -
      -
      -C = 5
      -alpha = 1 / (C * len(X))
      -
      -lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
      -svm_clf = SVC(kernel="linear", C=C)
      -sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
      -                        max_iter=100000, random_state=42)
      -
      -scaler = StandardScaler()
      -X_scaled = scaler.fit_transform(X)
      -
      -lin_clf.fit(X_scaled, y)
      -svm_clf.fit(X_scaled, y)
      -sgd_clf.fit(X_scaled, y)
      -
      -print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
      -print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
      -print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
      -
      -# Compute the slope and bias of each decision boundary
      -w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
      -b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
      -w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
      -b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
      -w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
      -b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
      -
      -# Transform the decision boundary lines back to the original scale
      -line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
      -line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
      -line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
      -
      -# Plot all three decision boundaries
      -plt.figure(figsize=(11, 4))
      -plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
      -plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
      -plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
      -plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
      -plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
      -plt.xlabel("Petal length", fontsize=14)
      -plt.ylabel("Petal width", fontsize=14)
      -plt.legend(loc="upper center", fontsize=14)
      -plt.axis([0, 5.5, 0, 2])
      -
      -plt.show()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - - -









      -

      What is a hyperplane?

      - -

      The aim of the SVM algorithm is to find a hyperplane in a -\( p \)-dimensional space, where \( p \) is the number of features that -distinctly classifies the data points. -

      - -

      In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). -As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is -a two-dimensional subspace, or stated simply, a plane. -

      - -

      In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as

      -$$ -b+w_1x_1+w_2x_2=0, -$$ - -

      where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line -\( b+w_1x_1+w_2x_2=0 \). -In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). -We can then rewrite the above equation as -

      - -$$ -\boldsymbol{x}^T\boldsymbol{w}+b=0. -$$ - - -









      -

      A \( p \)-dimensional space of features

      - -

      We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). -In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as -

      -$$ -b+wx_1+w_2x_2+\dots +w_px_p=0. -$$ - -

      If we define a -matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) -of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), -

      -$$ -\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. -$$ - -

      If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have

      -$$ -b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, -$$ - -

      if our output \( y_i=1 \). -In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if -

      -$$ -b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, -$$ - -

      for the class of observations \( y_i=-1 \), -then \( \boldsymbol{x}_i \) lies on the other side. -

      - -

      Equivalently, for the two classes of observations we have

      -$$ -y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. -$$ - -

      When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.

      +

      +
      +

      +
      +

      -

      The two-dimensional case

      - -

      Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional -plane. To separate the two classes of data points, there are many -possible lines (hyperplanes if you prefer a more strict naming) -that could be chosen. Our objective is to find a -plane that has the maximum margin, i.e the maximum distance between -data points of both classes. Maximizing the margin distance provides -some reinforcement so that future data points can be classified with -more confidence. -

      - -

      What a linear classifier attempts to accomplish is to split the -feature space into two half spaces by placing a hyperplane between the -data points. This hyperplane will be our decision boundary. All -points on one side of the plane will belong to class one and all points -on the other side of the plane will belong to the second class two. -

      - -

      Unfortunately there are many ways in which we can place a hyperplane -to divide the data. Below is an example of two candidate hyperplanes -for our data sample. -

      +

      The problem of exploding or vanishing gradients

      +
        +
      • What happens to the magnitude of the gradients as we backpropagate through many layers? +
          +
        1. If the weights are small, the gradients shrink exponentially.
        2. +
        3. If the weights are big the gradients grow exponentially.
        4. +
        +
      • Typical feed-forward neural nets can cope with these exponential effects because they only have a few hidden layers.
      • +
      • In an RNN trained on long sequences (e.g. 100 time steps) the gradients can easily explode or vanish. +
          +
        1. We can avoid this by initializing the weights very carefully.
        2. +
        +
      • Even with good initial weights, its very hard to detect that the current target output depends on an input from many time-steps ago.
      • +
      +

      RNNs have difficulty dealing with long-range dependencies.











      -

      Getting into the details

      +

      Four effective ways to learn an RNN

      +
        +
      1. Long Short Term Memory Make the RNN out of little modules that are designed to remember values for a long time.
      2. +
      3. Hessian Free Optimization: Deal with the vanishing gradients problem by using a fancy optimizer that can detect directions with a tiny gradient but even smaller curvature.
      4. +
      5. Echo State Networks: Initialize the input a hidden and hidden-hidden and output-hidden connections very carefully so that the hidden state has a huge reservoir of weakly coupled oscillators which can be selectively driven by the input.
      6. +
          +
        • ESNs only need to learn the hidden-output connections.
        • +
        +
      7. Good initialization with momentum Initialize like in Echo State Networks, but then learn all of the connections using momentum
      8. +
      +

      Long Short Term Memory (LSTM)

      -

      Let us define the function

      -$$ -f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, -$$ - -

      as the function that determines the line \( L \) that separates two classes (our two features), see the figure here.

      - -

      Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \).

      - -

      The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then

      -$$ -\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). -$$ - - -









      -

      First attempt at a minimization approach

      - -

      How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could -do is to define a cost function which now contains the set of all -misclassified points \( M \) and attempt to minimize this function +

      LSTM uses a memory cell for + modeling long-range dependencies and avoid vanishing gradient + problems.

      -$$ -C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). -$$ - -

      We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us

      -$$ -\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, -$$ - -

      and

      -$$ -\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. -$$ - - -









      -

      Solving the equations

      - -

      We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations

      -$$ -b \leftarrow b +\eta \frac{\partial C}{\partial b}, -$$ - -

      and

      -$$ -\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, -$$ - -

      where \( \eta \) is our by now well-known learning rate.

      - -









      -

      Code Example

      - -

      The equations we discussed above can be coded rather easily (the -framework is similar to what we developed for logistic -regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

        +
      1. Introduced by Hochreiter and Schmidhuber (1997) who solved the problem of getting an RNN to remember things for a long time (like hundreds of time steps).
      2. +
      3. They designed a memory cell using logistic and linear units with multiplicative interactions.
      4. +
      5. Information gets into the cell whenever its “write” gate is on.
      6. +
      7. The information stays in the cell so long as its keep gate is on.
      8. +
      9. Information can be read from the cell by turning on its read gate.
      10. +
      +

      Implementing a memory cell in a neural network

      +

      To preserve information for a long time in +the activities of an RNN, we use a circuit +that implements an analog memory cell.

      +
        +
      1. A linear unit that has a self-link with a weight of 1 will maintain its state.
      2. +
      3. Information is stored in the cell by activating its write gate.
      4. +
      5. Information is retrieved by activating the read gate.
      6. +
      7. We can backpropagate through this circuit because logistics are have nice derivatives.
      8. +
      +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +

      +
      +

      +
      +

      + +









      +

      An extrapolation example

      + +

      The following code provides an example of how recurrent neural +networks can be used to extrapolate to unknown values of physics data +sets. Specifically, the data sets used in this program come from +a quantum mechanical many-body calculation of energies as functions of the number of particles. +

      + +
      -
      +  
      # For matrices and calculations
      +import numpy as np
      +# For machine learning (backend for keras)
      +import tensorflow as tf
      +# User-friendly machine learning library
      +# Front end for TensorFlow
      +import tensorflow.keras
      +# Different methods from Keras needed to create an RNN
      +# This is not necessary but it shortened function calls 
      +# that need to be used in the code.
      +from tensorflow.keras import datasets, layers, models
      +from tensorflow.keras.layers import Input
      +from tensorflow.keras import regularizers
      +from tensorflow.keras.models import Model, Sequential
      +from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
      +# For timing the code
      +from timeit import default_timer as timer
      +# For plotting
      +import matplotlib.pyplot as plt
      +
      +
      +# The data set
      +datatype='VaryDimension'
      +X_tot = np.arange(2, 42, 2)
      +y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
      +	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
      +	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
       
      @@ -1366,328 +1239,615 @@ regression). We are going to set up a simple case with two classes only and we w









      -

      Problems with the Simpler Approach

      +

      Formatting the Data

      -

      There are however problems with this approach, although it looks -pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. +

      The way the recurrent neural networks are trained in this program +differs from how machine learning algorithms are usually trained. +Typically a machine learning algorithm is trained by learning the +relationship between the x data and the y data. In this program, the +recurrent neural network will be trained to recognize the relationship +in a sequence of y values. This is type of data formatting is +typically used time series forcasting, but it can also be used in any +extrapolation (time series forecasting is just a specific type of +extrapolation along the time axis). This method of data formatting +does not use the x data and assumes that the y data are evenly spaced.

      -

      For small -gaps between the entries, we may also end up needing many iterations -before the solutions converge and if the data cannot be separated -properly into two distinct classes, we may not experience a converge -at all. +

      For a standard machine learning algorithm, the training data has the +form of (x,y) so the machine learning algorithm learns to assiciate a +y value with a given x value. This is useful when the test data has x +values within the same range as the training data. However, for this +application, the x values of the test data are outside of the x values +of the training data and the traditional method of training a machine +learning algorithm does not work as well. For this reason, the +recurrent neural network is trained on sequences of y values of the +form ((y1, y2), y3), so that the network is concerned with learning +the pattern of the y data and not the relation between the x and y +data. As long as the pattern of y data outside of the training region +stays relatively stable compared to what was inside the training +region, this method of training can produce accurate extrapolations to +y values far removed from the training data set.

      -









      -

      A better approach

      + + + + + + -

      A better approach is rather to try to define a large margin between -the two classes (if they are well separated from the beginning). -

      -

      Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to -\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition -

      + +
      +
      +
      +
      +
      +
      # FORMAT_DATA
      +def format_data(data, length_of_sequence = 2):  
      +    """
      +        Inputs:
      +            data(a numpy array): the data that will be the inputs to the recurrent neural
      +                network
      +            length_of_sequence (an int): the number of elements in one iteration of the
      +                sequence patter.  For a function approximator use length_of_sequence = 2.
      +        Returns:
      +            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
      +                dimensions are length of data - length of sequence, length of sequence, 
      +                dimnsion of data
      +            rnn_output (a numpy array): the training data for the neural network
      +        Formats data to be used in a recurrent neural network.
      +    """
       
      -$$
      -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. 
      -$$
      +    X, Y = [], []
      +    for i in range(len(data)-length_of_sequence):
      +        # Get the next length_of_sequence elements
      +        a = data[i:i+length_of_sequence]
      +        # Get the element that immediately follows that
      +        b = data[i+length_of_sequence]
      +        # Reshape so that each data point is contained in its own array
      +        a = np.reshape (a, (len(a), 1))
      +        X.append(a)
      +        Y.append(b)
      +    rnn_input = np.array(X)
      +    rnn_output = np.array(Y)
       
      -

      All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line.

      + return rnn_input, rnn_output -

      We seek thus the largest value \( M \) defined by

      -$$ -\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, -$$ -

      or just

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. -$$ +# ## Defining the Recurrent Neural Network Using Keras +# +# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer. -

      If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of -\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition -

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. -$$ - -

      We have thus defined our margin as the invers of the norm of -\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as -possible margin \( M \). Before we proceed, we need to remind ourselves -about Lagrangian multipliers. -

      - -









      -

      A quick Reminder on Lagrangian Multipliers

      - -

      Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an -extreme we have -

      -$$ -df=0. -$$ - -

      A necessary and sufficient condition is

      -$$ -\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, -$$ - -

      due to

      -$$ -df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. -$$ - -

      In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) -so that they are no longer all independent. It is possible at least in principle to use each -constraint to eliminate one variable -and to proceed with a new and smaller set of independent varables. -

      - -

      The use of so-called Lagrangian multipliers is an alternative technique when the elimination -of variables is incovenient or undesirable. Assume that we have an equation of constraint on -the variables \( x,y,z \) -

      -$$ -\phi(x,y,z) = 0, -$$ - -

      resulting in

      -$$ -d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. -$$ - -

      Now we cannot set anymore

      -$$ -\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, -$$ - -

      if \( df=0 \) is wanted -because there are now only two independent variables! Assume \( x \) and \( y \) are the independent -variables. -Then \( dz \) is no longer arbitrary. -

      - -









      -

      Adding the Multiplier

      - -

      However, we can add to

      -$$ -df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, -$$ - -

      a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in

      -$$ -df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda -\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ -(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. -$$ - -

      Our multiplier is chosen so that

      -$$ -\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. -$$ - -

      We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have

      -$$ -\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, -$$ - -

      and

      -$$ -\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. -$$ - -

      When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and -\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, -it is therefore often called -Lagrange's undetermined multiplier. -If we have a set of constraints \( \phi_k \) we have the equations -

      -$$ -\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. -$$ +def rnn(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with one hidden layer and returns the model. + """ + # Number of neurons in the input and output layers + in_out_neurons = 1 + # Number of neurons in the hidden layer + hidden_neurons = 200 + # Define the input layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to + # the network immediately after the input layer + rnn = SimpleRNN(hidden_neurons, + return_sequences=False, + stateful = stateful, + name="RNN")(inp) + # Define the output layer as a dense neural network layer (standard neural network layer) + #and add it to the network immediately after the hidden layer. + dens = Dense(in_out_neurons,name="dense")(rnn) + # Create the machine learning model starting with the input layer and ending with the + # output layer + model = Model(inputs=[inp],outputs=[dens]) + # Compile the machine learning model using the mean squared error function as the loss + # function and an Adams optimizer. + model.compile(loss="mean_squared_error", optimizer="adam") + return model +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +










      -

      Setting up the Problem

      -

      In order to solve the above problem, we define the following Lagrangian function to be minimized

      -$$ -{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], -$$ +

      Predicting New Points With A Trained Recurrent Neural Network

      -

      where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).

      -

      Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

      -$$ -\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, -$$ + +
      +
      +
      +
      +
      +
      def test_rnn (x1, y_test, plot_min, plot_max):
      +    """
      +        Inputs:
      +            x1 (a list or numpy array): The complete x component of the data set
      +            y_test (a list or numpy array): The complete y component of the data set
      +            plot_min (an int or float): the smallest x value used in the training data
      +            plot_max (an int or float): the largest x valye used in the training data
      +        Returns:
      +            None.
      +        Uses a trained recurrent neural network model to predict future points in the 
      +        series.  Computes the MSE of the predicted data set from the true data set, saves
      +        the predicted data set to a csv file, and plots the predicted and true data sets w
      +        while also displaying the data range used for training.
      +    """
      +    # Add the training data as the first dim points in the predicted data array as these
      +    # are known values.
      +    y_pred = y_test[:dim].tolist()
      +    # Generate the first input to the trained recurrent neural network using the last two 
      +    # points of the training data.  Based on how the network was trained this means that it
      +    # will predict the first point in the data set after the training data.  All of the 
      +    # brackets are necessary for Tensorflow.
      +    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
      +    # Save the very last point in the training data set.  This will be used later.
      +    last = [y_test[dim-1]]
       
      -

      and

      -$$ -\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. -$$ + # Iterate until the complete data set is created. + for i in range (dim, len(y_test)): + # Predict the next point in the data set using the previous two points. + next = model.predict(next_input) + # Append just the number of the predicted data set + y_pred.append(next[0][0]) + # Create the input that will be used to predict the next data point in the data set. + next_input = np.array([[last, next[0]]], dtype=np.float64) + last = next -

      Inserting these constraints into the equation for \( {\cal L} \) we obtain

      -$$ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, -$$ + # Print the mean squared error between the known data set and the predicted data set. + print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean()) + # Save the predicted data set as a csv file for later use + name = datatype + 'Predicted'+str(dim)+'.csv' + np.savetxt(name, y_pred, delimiter=',') + # Plot the known data set and the predicted data set. The red box represents the region that was used + # for the training data. + fig, ax = plt.subplots() + ax.plot(x1, y_test, label="true", linewidth=3) + ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4) + ax.legend() + # Created a red region to represent the points used in the training data. + ax.axvspan(plot_min, plot_max, alpha=0.25, color='red') + plt.show() -

      subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). -We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition -

      -$$ -\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. -$$ +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + + +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +model = rnn(length_of_sequences = rnn_input.shape[1]) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      -
        -
      1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
      2. -
      3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
      4. -
      -

      When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \).











      -

      The problem to solve

      +

      Other Things to Try

      -

      We can rewrite

      -$$ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, -$$ - -

      and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem

      -$$ -\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ -y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ -\dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots \\ -y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ -\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, -$$ - -

      subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and -\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

      Changing the size of the recurrent neural network and its parameters +can drastically change the results you get from the model. The below +code takes the simple recurrent neural network from above and adds a +second hidden layer, changes the number of neurons in the hidden +layer, and explicitly declares the activation function of the hidden +layers to be a sigmoid function. The loss function and optimizer can +also be changed but are kept the same as the above network. These +parameters can be tuned to provide the optimal result from the +network. For some ideas on how to improve the performance of a +recurrent neural network.

      + + +
      +
      +
      +
      +
      +
      def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
      +    """
      +        Inputs:
      +            length_of_sequences (an int): the number of y values in "x data".  This is determined
      +                when the data is formatted
      +            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
      +            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
      +        Returns:
      +            model (a Keras model): The recurrent neural network that is built and compiled by this
      +                method
      +        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
      +    """
      +    # Number of neurons in the input and output layers
      +    in_out_neurons = 1
      +    # Number of neurons in the hidden layer, increased from the first network
      +    hidden_neurons = 500
      +    # Define the input layer
      +    inp = Input(batch_shape=(batch_size, 
      +                length_of_sequences, 
      +                in_out_neurons))  
      +    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
      +    # function to be the sigmoid function (the default value is hyperbolic tangent)
      +    rnn1 = SimpleRNN(hidden_neurons, 
      +                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
      +                    stateful = stateful, activation = 'sigmoid',
      +                    name="RNN1")(inp)
      +    rnn2 = SimpleRNN(hidden_neurons, 
      +                    return_sequences=False, activation = 'sigmoid',
      +                    stateful = stateful,
      +                    name="RNN2")(rnn1)
      +    # Define the output layer as a dense neural network layer (standard neural network layer)
      +    #and add it to the network immediately after the hidden layer.
      +    dens = Dense(in_out_neurons,name="dense")(rnn2)
      +    # Create the machine learning model starting with the input layer and ending with the 
      +    # output layer
      +    model = Model(inputs=[inp],outputs=[dens])
      +    # Compile the machine learning model using the mean squared error function as the loss 
      +    # function and an Adams optimizer.
      +    model.compile(loss="mean_squared_error", optimizer="adam")  
      +    return model
      +
      +# Check to make sure the data set is complete
      +assert len(X_tot) == len(y_tot)
      +
      +# This is the number of points that will be used in as the training data
      +dim=12
      +
      +# Separate the training data from the whole data set
      +X_train = X_tot[:dim]
      +y_train = y_tot[:dim]
      +
      +
      +# Generate the training data for the RNN, using a sequence of 2
      +rnn_input, rnn_training = format_data(y_train, 2)
      +
      +
      +# Create a recurrent neural network in Keras and produce a summary of the 
      +# machine learning model
      +model = rnn_2layers(length_of_sequences = 2)
      +model.summary()
      +
      +# Start the timer.  Want to time training+testing
      +start = timer()
      +# Fit the model using the training data genenerated above using 150 training iterations and a 5%
      +# validation split.  Setting verbose to True prints information about each training iteration.
      +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
      +                 verbose=True,validation_split=0.05)
      +
      +
      +# This section plots the training loss and the validation loss as a function of training iteration.
      +# This is not required for analyzing the couple cluster data but can help determine if the network is
      +# being overtrained.
      +for label in ["loss","val_loss"]:
      +    plt.plot(hist.history[label],label=label)
      +
      +plt.ylabel("loss")
      +plt.xlabel("epoch")
      +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
      +plt.legend()
      +plt.show()
      +
      +# Use the trained neural network to predict more points of the data set
      +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
      +# Stop the timer and calculate the total time needed.
      +end = timer()
      +print('Time: ', end-start)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +









      -

      The last steps

      +

      Other Types of Recurrent Neural Networks

      -

      Solving the above problem, yields the values of \( \lambda_i \). -To find the coefficients of your hyperplane we need simply to compute -

      -$$ -\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. -$$ - -

      With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, -$$ - -

      resulting in

      -$$ -b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, -$$ - -

      or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have

      -$$ -b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). -$$ - -

      With our hyperplane coefficients we can use our classifier to assign any observation by simply using

      -$$ -y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). -$$ - -

      Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier.

      - -









      -

      A soft classifier

      - -

      Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.

      - -

      Suppose now that classes overlap in feature space, as shown in the -figure here. One way to deal with this problem before we define the -so-called kernel approach, is to allow a kind of slack in the sense -that we allow some points to be on the wrong side of the margin. +

      Besides a simple recurrent neural network layer, there are two other +commonly used types of recurrent neural network layers: Long Short +Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short +introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b +and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b.

      -

      We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and -modify our previous equation -

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, -$$ - -

      to

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, -$$ - -

      with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). -The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction -\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), -we bound the total amount by which predictions fall on the wrong side of their margins. +

      The first network created below is similar to the previous network, +but it replaces the SimpleRNN layers with LSTM layers. The second +network below has two hidden layers made up of GRUs, which are +preceeded by two dense (feeddorward) neural network layers. These +dense layers "preprocess" the data before it reaches the recurrent +layers. This architecture has been shown to improve the performance +of recurrent neural networks (see the link above and also +https://arxiv.org/pdf/1807.02857.pdf.

      -

      Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of -misclassifications. -

      -









      -

      Soft optmization problem

      + +
      +
      +
      +
      +
      +
      def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
      +    """
      +        Inputs:
      +            length_of_sequences (an int): the number of y values in "x data".  This is determined
      +                when the data is formatted
      +            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
      +            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
      +        Returns:
      +            model (a Keras model): The recurrent neural network that is built and compiled by this
      +                method
      +        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
      +    """
      +    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
      +    in_out_neurons = 1
      +    hidden_neurons = 250
      +    # Input Layer
      +    inp = Input(batch_shape=(batch_size, 
      +                length_of_sequences, 
      +                in_out_neurons)) 
      +    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
      +    rnn= LSTM(hidden_neurons, 
      +                    return_sequences=True,
      +                    stateful = stateful,
      +                    name="RNN", use_bias=True, activation='tanh')(inp)
      +    rnn1 = LSTM(hidden_neurons, 
      +                    return_sequences=False,
      +                    stateful = stateful,
      +                    name="RNN1", use_bias=True, activation='tanh')(rnn)
      +    # Output layer
      +    dens = Dense(in_out_neurons,name="dense")(rnn1)
      +    # Define the midel
      +    model = Model(inputs=[inp],outputs=[dens])
      +    # Compile the model
      +    model.compile(loss='mean_squared_error', optimizer='adam')  
      +    # Return the model
      +    return model
       
      -

      This has in turn the consequences that we change our optmization problem to finding the minimum of

      -$$ -{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, -$$ +def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False): + """ + Inputs: + length_of_sequences (an int): the number of y values in "x data". This is determined + when the data is formatted + batch_size (an int): Default value is None. See Keras documentation of SimpleRNN. + stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN. + Returns: + model (a Keras model): The recurrent neural network that is built and compiled by this + method + Builds and compiles a recurrent neural network with four hidden layers (two dense followed by + two GRU layers) and returns the model. + """ + # Number of neurons on the input/output layers and hidden layers + in_out_neurons = 1 + hidden_neurons = 250 + # Input layer + inp = Input(batch_shape=(batch_size, + length_of_sequences, + in_out_neurons)) + # Hidden Dense (feedforward) layers + dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp) + dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn) + # Hidden GRU layers + rnn1 = GRU(hidden_neurons, + return_sequences=True, + stateful = stateful, + name="RNN1", use_bias=True)(dnn1) + rnn = GRU(hidden_neurons, + return_sequences=False, + stateful = stateful, + name="RNN", use_bias=True)(rnn1) + # Output layer + dens = Dense(in_out_neurons,name="dense")(rnn) + # Define the model + model = Model(inputs=[inp],outputs=[dens]) + # Compile the mdoel + model.compile(loss='mean_squared_error', optimizer='adam') + # Return the model + return model -

      subject to

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, -$$ +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) -

      with the requirement \( \xi_i\geq 0 \).

      +# This is the number of points that will be used in as the training data +dim=12 -

      Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

      -$$ -\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, -$$ +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] -

      and

      -$$ -\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, -$$ -

      and

      -$$ -\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. -$$ +# Generate the training data for the RNN, using a sequence of 2 +rnn_input, rnn_training = format_data(y_train, 2) -

      Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before

      -$$ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, -$$ -

      but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). -We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads -

      -$$ -\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, -$$ +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +# Change the method name to reflect which network you want to use +model = dnn2_gru2(length_of_sequences = 2) +model.summary() -$$ -\gamma_i\xi_i = 0, -$$ +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict more points of the data set +test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1]) +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) + + +# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data) +# +# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation. + +# Check to make sure the data set is complete +assert len(X_tot) == len(y_tot) + +# This is the number of points that will be used in as the training data +dim=12 + +# Separate the training data from the whole data set +X_train = X_tot[:dim] +y_train = y_tot[:dim] + +# Reshape the data for Keras specifications +X_train = X_train.reshape((dim, 1)) +y_train = y_train.reshape((dim, 1)) + + +# Create a recurrent neural network in Keras and produce a summary of the +# machine learning model +# Set the sequence length to 1 for regular data formatting +model = rnn(length_of_sequences = 1) +model.summary() + +# Start the timer. Want to time training+testing +start = timer() +# Fit the model using the training data genenerated above using 150 training iterations and a 5% +# validation split. Setting verbose to True prints information about each training iteration. +hist = model.fit(X_train, y_train, batch_size=None, epochs=150, + verbose=True,validation_split=0.05) + + +# This section plots the training loss and the validation loss as a function of training iteration. +# This is not required for analyzing the couple cluster data but can help determine if the network is +# being overtrained. +for label in ["loss","val_loss"]: + plt.plot(hist.history[label],label=label) + +plt.ylabel("loss") +plt.xlabel("epoch") +plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1])) +plt.legend() +plt.show() + +# Use the trained neural network to predict the remaining data points +X_pred = X_tot[dim:] +X_pred = X_pred.reshape((len(X_pred), 1)) +y_model = model.predict(X_pred) +y_pred = np.concatenate((y_tot[:dim], y_model.flatten())) + +# Plot the known data set and the predicted data set. The red box represents the region that was used +# for the training data. +fig, ax = plt.subplots() +ax.plot(X_tot, y_tot, label="true", linewidth=3) +ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4) +ax.legend() +# Created a red region to represent the points used in the training data. +ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red') +plt.show() + +# Stop the timer and calculate the total time needed. +end = timer() +print('Time: ', end-start) +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      -

      and

      -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. -$$
      - © 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
      diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html index 92d7149e1..9b9ec5553 100644 --- a/doc/pub/week45/html/week45.html +++ b/doc/pub/week45/html/week45.html @@ -8,8 +8,8 @@ doconce format html week45.do.txt --pygments_html_style=default --html_style=blo - -Week 45: Decisions Trees, Random Forests, Bagging and Boosting + +Week 45, Recurrent Neural Networks