802 KiB
802 KiB
In [1]:
%matplotlib inline
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()In [2]:
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)}")GridSearchCV(estimator=Ridge(),
param_grid={'alpha': array([1.00000000e-04, 4.64158883e-04, 2.15443469e-03, 1.00000000e-02,
4.64158883e-02, 2.15443469e-01, 1.00000000e+00, 4.64158883e+00,
2.15443469e+01, 1.00000000e+02])})
Best estimated lambda-value: 100.0
MSE score: 1.0892144853354966
R2 score: -0.0038332550504751595
In [3]:
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)}")RandomizedSearchCV(estimator=Ridge(), n_iter=100,
param_distributions={'alpha': <scipy.stats._distn_infrastructure.rv_frozen object at 0x1646da640>})
Best estimated lambda-value: 0.9849967686928113
MSE score: 1.0853136633465326
R2 score: -0.0002382102844775691
In [4]:
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)))(426, 30) (143, 30) Test set accuracy with Logistic Regression: 0.94
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
In [5]:
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()In [6]:
cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)In [7]:
correlation_matrix = cancerpd.corr().round(1)In [8]:
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()(426, 30) (143, 30) [1. 0.86666667 1. 0.92857143 1. 0.85714286 1. 0.92857143 0.92857143 1. ] Test set accuracy with Logistic Regression: 0.94
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/linear_model/_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
In [9]:
# Start importing packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
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
# 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()Metal device set to: Apple M1 Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
simple_rnn (SimpleRNN) (None, 32) 1184
dense (Dense) (None, 8) 264
dense_1 (Dense) (None, 1) 9
=================================================================
Total params: 1,457
Trainable params: 1,457
Non-trainable params: 0
_________________________________________________________________
Epoch 1/100
2023-11-21 06:15:36.594141: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz
50/50 - 1s - loss: 0.6155 - 1s/epoch - 20ms/step
Epoch 2/100
50/50 - 0s - loss: 0.4372 - 444ms/epoch - 9ms/step
Epoch 3/100
50/50 - 0s - loss: 0.4090 - 443ms/epoch - 9ms/step
Epoch 4/100
50/50 - 0s - loss: 0.4011 - 441ms/epoch - 9ms/step
Epoch 5/100
50/50 - 0s - loss: 0.3967 - 440ms/epoch - 9ms/step
Epoch 6/100
50/50 - 0s - loss: 0.3961 - 439ms/epoch - 9ms/step
Epoch 7/100
50/50 - 0s - loss: 0.3966 - 443ms/epoch - 9ms/step
Epoch 8/100
50/50 - 0s - loss: 0.3936 - 442ms/epoch - 9ms/step
Epoch 9/100
50/50 - 0s - loss: 0.3915 - 444ms/epoch - 9ms/step
Epoch 10/100
50/50 - 0s - loss: 0.3908 - 446ms/epoch - 9ms/step
Epoch 11/100
50/50 - 0s - loss: 0.3897 - 446ms/epoch - 9ms/step
Epoch 12/100
50/50 - 0s - loss: 0.3897 - 446ms/epoch - 9ms/step
Epoch 13/100
50/50 - 0s - loss: 0.3896 - 446ms/epoch - 9ms/step
Epoch 14/100
50/50 - 0s - loss: 0.3881 - 445ms/epoch - 9ms/step
Epoch 15/100
50/50 - 0s - loss: 0.3876 - 445ms/epoch - 9ms/step
Epoch 16/100
50/50 - 0s - loss: 0.3861 - 444ms/epoch - 9ms/step
Epoch 17/100
50/50 - 0s - loss: 0.3860 - 446ms/epoch - 9ms/step
Epoch 18/100
50/50 - 0s - loss: 0.3831 - 448ms/epoch - 9ms/step
Epoch 19/100
50/50 - 0s - loss: 0.3857 - 446ms/epoch - 9ms/step
Epoch 20/100
50/50 - 0s - loss: 0.3854 - 446ms/epoch - 9ms/step
Epoch 21/100
50/50 - 0s - loss: 0.3856 - 446ms/epoch - 9ms/step
Epoch 22/100
50/50 - 0s - loss: 0.3845 - 448ms/epoch - 9ms/step
Epoch 23/100
50/50 - 0s - loss: 0.3831 - 446ms/epoch - 9ms/step
Epoch 24/100
50/50 - 0s - loss: 0.3839 - 446ms/epoch - 9ms/step
Epoch 25/100
50/50 - 0s - loss: 0.3827 - 446ms/epoch - 9ms/step
Epoch 26/100
50/50 - 0s - loss: 0.3814 - 448ms/epoch - 9ms/step
Epoch 27/100
50/50 - 0s - loss: 0.3829 - 445ms/epoch - 9ms/step
Epoch 28/100
50/50 - 0s - loss: 0.3814 - 444ms/epoch - 9ms/step
Epoch 29/100
50/50 - 0s - loss: 0.3810 - 446ms/epoch - 9ms/step
Epoch 30/100
50/50 - 0s - loss: 0.3803 - 446ms/epoch - 9ms/step
Epoch 31/100
50/50 - 0s - loss: 0.3805 - 446ms/epoch - 9ms/step
Epoch 32/100
50/50 - 0s - loss: 0.3812 - 446ms/epoch - 9ms/step
Epoch 33/100
50/50 - 0s - loss: 0.3812 - 447ms/epoch - 9ms/step
Epoch 34/100
50/50 - 0s - loss: 0.3794 - 444ms/epoch - 9ms/step
Epoch 35/100
50/50 - 0s - loss: 0.3778 - 447ms/epoch - 9ms/step
Epoch 36/100
50/50 - 0s - loss: 0.3787 - 446ms/epoch - 9ms/step
Epoch 37/100
50/50 - 0s - loss: 0.3802 - 445ms/epoch - 9ms/step
Epoch 38/100
50/50 - 0s - loss: 0.3758 - 447ms/epoch - 9ms/step
Epoch 39/100
50/50 - 0s - loss: 0.3795 - 445ms/epoch - 9ms/step
Epoch 40/100
50/50 - 0s - loss: 0.3788 - 444ms/epoch - 9ms/step
Epoch 41/100
50/50 - 0s - loss: 0.3701 - 447ms/epoch - 9ms/step
Epoch 42/100
50/50 - 0s - loss: 0.3802 - 443ms/epoch - 9ms/step
Epoch 43/100
50/50 - 0s - loss: 0.3770 - 444ms/epoch - 9ms/step
Epoch 44/100
50/50 - 0s - loss: 0.3758 - 446ms/epoch - 9ms/step
Epoch 45/100
50/50 - 0s - loss: 0.3763 - 446ms/epoch - 9ms/step
Epoch 46/100
50/50 - 0s - loss: 0.3768 - 446ms/epoch - 9ms/step
Epoch 47/100
50/50 - 0s - loss: 0.3745 - 445ms/epoch - 9ms/step
Epoch 48/100
50/50 - 0s - loss: 0.3773 - 443ms/epoch - 9ms/step
Epoch 49/100
50/50 - 0s - loss: 0.3753 - 447ms/epoch - 9ms/step
Epoch 50/100
50/50 - 0s - loss: 0.3747 - 446ms/epoch - 9ms/step
Epoch 51/100
50/50 - 0s - loss: 0.3750 - 440ms/epoch - 9ms/step
Epoch 52/100
50/50 - 0s - loss: 0.3740 - 448ms/epoch - 9ms/step
Epoch 53/100
50/50 - 0s - loss: 0.3767 - 448ms/epoch - 9ms/step
Epoch 54/100
50/50 - 0s - loss: 0.3745 - 455ms/epoch - 9ms/step
Epoch 55/100
50/50 - 0s - loss: 0.3750 - 452ms/epoch - 9ms/step
Epoch 56/100
50/50 - 0s - loss: 0.3730 - 452ms/epoch - 9ms/step
Epoch 57/100
50/50 - 0s - loss: 0.3728 - 452ms/epoch - 9ms/step
Epoch 58/100
50/50 - 0s - loss: 0.3736 - 451ms/epoch - 9ms/step
Epoch 59/100
50/50 - 0s - loss: 0.3727 - 450ms/epoch - 9ms/step
Epoch 60/100
50/50 - 0s - loss: 0.3732 - 453ms/epoch - 9ms/step
Epoch 61/100
50/50 - 0s - loss: 0.3705 - 451ms/epoch - 9ms/step
Epoch 62/100
[0;31m---------------------------------------------------------------------------[0m [0;31mKeyboardInterrupt[0m Traceback (most recent call last) Input [0;32mIn [9][0m, in [0;36m<cell line: 53>[0;34m()[0m [1;32m 50[0m model[38;5;241m.[39mcompile(loss[38;5;241m=[39m[38;5;124m'[39m[38;5;124mmean_squared_error[39m[38;5;124m'[39m, optimizer[38;5;241m=[39m[38;5;124m'[39m[38;5;124mrmsprop[39m[38;5;124m'[39m) [1;32m 51[0m model[38;5;241m.[39msummary() [0;32m---> 53[0m [43mmodel[49m[38;5;241;43m.[39;49m[43mfit[49m[43m([49m[43mtrainX[49m[43m,[49m[43mtrainY[49m[43m,[49m[43m [49m[43mepochs[49m[38;5;241;43m=[39;49m[38;5;241;43m100[39;49m[43m,[49m[43m [49m[43mbatch_size[49m[38;5;241;43m=[39;49m[38;5;241;43m16[39;49m[43m,[49m[43m [49m[43mverbose[49m[38;5;241;43m=[39;49m[38;5;241;43m2[39;49m[43m)[49m [1;32m 54[0m trainPredict [38;5;241m=[39m model[38;5;241m.[39mpredict(trainX) [1;32m 55[0m testPredict[38;5;241m=[39m model[38;5;241m.[39mpredict(testX) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/keras/utils/traceback_utils.py:64[0m, in [0;36mfilter_traceback.<locals>.error_handler[0;34m(*args, **kwargs)[0m [1;32m 62[0m filtered_tb [38;5;241m=[39m [38;5;28;01mNone[39;00m [1;32m 63[0m [38;5;28;01mtry[39;00m: [0;32m---> 64[0m [38;5;28;01mreturn[39;00m [43mfn[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 65[0m [38;5;28;01mexcept[39;00m [38;5;167;01mException[39;00m [38;5;28;01mas[39;00m e: [38;5;66;03m# pylint: disable=broad-except[39;00m [1;32m 66[0m filtered_tb [38;5;241m=[39m _process_traceback_frames(e[38;5;241m.[39m__traceback__) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/keras/engine/training.py:1384[0m, in [0;36mModel.fit[0;34m(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)[0m [1;32m 1377[0m [38;5;28;01mwith[39;00m tf[38;5;241m.[39mprofiler[38;5;241m.[39mexperimental[38;5;241m.[39mTrace( [1;32m 1378[0m [38;5;124m'[39m[38;5;124mtrain[39m[38;5;124m'[39m, [1;32m 1379[0m epoch_num[38;5;241m=[39mepoch, [1;32m 1380[0m step_num[38;5;241m=[39mstep, [1;32m 1381[0m batch_size[38;5;241m=[39mbatch_size, [1;32m 1382[0m _r[38;5;241m=[39m[38;5;241m1[39m): [1;32m 1383[0m callbacks[38;5;241m.[39mon_train_batch_begin(step) [0;32m-> 1384[0m tmp_logs [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mtrain_function[49m[43m([49m[43miterator[49m[43m)[49m [1;32m 1385[0m [38;5;28;01mif[39;00m data_handler[38;5;241m.[39mshould_sync: [1;32m 1386[0m context[38;5;241m.[39masync_wait() File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py:150[0m, in [0;36mfilter_traceback.<locals>.error_handler[0;34m(*args, **kwargs)[0m [1;32m 148[0m filtered_tb [38;5;241m=[39m [38;5;28;01mNone[39;00m [1;32m 149[0m [38;5;28;01mtry[39;00m: [0;32m--> 150[0m [38;5;28;01mreturn[39;00m [43mfn[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 151[0m [38;5;28;01mexcept[39;00m [38;5;167;01mException[39;00m [38;5;28;01mas[39;00m e: [1;32m 152[0m filtered_tb [38;5;241m=[39m _process_traceback_frames(e[38;5;241m.[39m__traceback__) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py:915[0m, in [0;36mFunction.__call__[0;34m(self, *args, **kwds)[0m [1;32m 912[0m compiler [38;5;241m=[39m [38;5;124m"[39m[38;5;124mxla[39m[38;5;124m"[39m [38;5;28;01mif[39;00m [38;5;28mself[39m[38;5;241m.[39m_jit_compile [38;5;28;01melse[39;00m [38;5;124m"[39m[38;5;124mnonXla[39m[38;5;124m"[39m [1;32m 914[0m [38;5;28;01mwith[39;00m OptionalXlaContext([38;5;28mself[39m[38;5;241m.[39m_jit_compile): [0;32m--> 915[0m result [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_call[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwds[49m[43m)[49m [1;32m 917[0m new_tracing_count [38;5;241m=[39m [38;5;28mself[39m[38;5;241m.[39mexperimental_get_tracing_count() [1;32m 918[0m without_tracing [38;5;241m=[39m (tracing_count [38;5;241m==[39m new_tracing_count) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py:947[0m, in [0;36mFunction._call[0;34m(self, *args, **kwds)[0m [1;32m 944[0m [38;5;28mself[39m[38;5;241m.[39m_lock[38;5;241m.[39mrelease() [1;32m 945[0m [38;5;66;03m# In this case we have created variables on the first call, so we run the[39;00m [1;32m 946[0m [38;5;66;03m# defunned version which is guaranteed to never create variables.[39;00m [0;32m--> 947[0m [38;5;28;01mreturn[39;00m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_stateless_fn[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwds[49m[43m)[49m [38;5;66;03m# pylint: disable=not-callable[39;00m [1;32m 948[0m [38;5;28;01melif[39;00m [38;5;28mself[39m[38;5;241m.[39m_stateful_fn [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m: [1;32m 949[0m [38;5;66;03m# Release the lock early so that multiple threads can perform the call[39;00m [1;32m 950[0m [38;5;66;03m# in parallel.[39;00m [1;32m 951[0m [38;5;28mself[39m[38;5;241m.[39m_lock[38;5;241m.[39mrelease() File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/function.py:2956[0m, in [0;36mFunction.__call__[0;34m(self, *args, **kwargs)[0m [1;32m 2953[0m [38;5;28;01mwith[39;00m [38;5;28mself[39m[38;5;241m.[39m_lock: [1;32m 2954[0m (graph_function, [1;32m 2955[0m filtered_flat_args) [38;5;241m=[39m [38;5;28mself[39m[38;5;241m.[39m_maybe_define_function(args, kwargs) [0;32m-> 2956[0m [38;5;28;01mreturn[39;00m [43mgraph_function[49m[38;5;241;43m.[39;49m[43m_call_flat[49m[43m([49m [1;32m 2957[0m [43m [49m[43mfiltered_flat_args[49m[43m,[49m[43m [49m[43mcaptured_inputs[49m[38;5;241;43m=[39;49m[43mgraph_function[49m[38;5;241;43m.[39;49m[43mcaptured_inputs[49m[43m)[49m File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/function.py:1853[0m, in [0;36mConcreteFunction._call_flat[0;34m(self, args, captured_inputs, cancellation_manager)[0m [1;32m 1849[0m possible_gradient_type [38;5;241m=[39m gradients_util[38;5;241m.[39mPossibleTapeGradientTypes(args) [1;32m 1850[0m [38;5;28;01mif[39;00m (possible_gradient_type [38;5;241m==[39m gradients_util[38;5;241m.[39mPOSSIBLE_GRADIENT_TYPES_NONE [1;32m 1851[0m [38;5;129;01mand[39;00m executing_eagerly): [1;32m 1852[0m [38;5;66;03m# No tape is watching; skip to running the function.[39;00m [0;32m-> 1853[0m [38;5;28;01mreturn[39;00m [38;5;28mself[39m[38;5;241m.[39m_build_call_outputs([38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_inference_function[49m[38;5;241;43m.[39;49m[43mcall[49m[43m([49m [1;32m 1854[0m [43m [49m[43mctx[49m[43m,[49m[43m [49m[43margs[49m[43m,[49m[43m [49m[43mcancellation_manager[49m[38;5;241;43m=[39;49m[43mcancellation_manager[49m[43m)[49m) [1;32m 1855[0m forward_backward [38;5;241m=[39m [38;5;28mself[39m[38;5;241m.[39m_select_forward_and_backward_functions( [1;32m 1856[0m args, [1;32m 1857[0m possible_gradient_type, [1;32m 1858[0m executing_eagerly) [1;32m 1859[0m forward_function, args_with_tangents [38;5;241m=[39m forward_backward[38;5;241m.[39mforward() File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/function.py:499[0m, in [0;36m_EagerDefinedFunction.call[0;34m(self, ctx, args, cancellation_manager)[0m [1;32m 497[0m [38;5;28;01mwith[39;00m _InterpolateFunctionError([38;5;28mself[39m): [1;32m 498[0m [38;5;28;01mif[39;00m cancellation_manager [38;5;129;01mis[39;00m [38;5;28;01mNone[39;00m: [0;32m--> 499[0m outputs [38;5;241m=[39m [43mexecute[49m[38;5;241;43m.[39;49m[43mexecute[49m[43m([49m [1;32m 500[0m [43m [49m[38;5;28;43mstr[39;49m[43m([49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43msignature[49m[38;5;241;43m.[39;49m[43mname[49m[43m)[49m[43m,[49m [1;32m 501[0m [43m [49m[43mnum_outputs[49m[38;5;241;43m=[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_num_outputs[49m[43m,[49m [1;32m 502[0m [43m [49m[43minputs[49m[38;5;241;43m=[39;49m[43margs[49m[43m,[49m [1;32m 503[0m [43m [49m[43mattrs[49m[38;5;241;43m=[39;49m[43mattrs[49m[43m,[49m [1;32m 504[0m [43m [49m[43mctx[49m[38;5;241;43m=[39;49m[43mctx[49m[43m)[49m [1;32m 505[0m [38;5;28;01melse[39;00m: [1;32m 506[0m outputs [38;5;241m=[39m execute[38;5;241m.[39mexecute_with_cancellation( [1;32m 507[0m [38;5;28mstr[39m([38;5;28mself[39m[38;5;241m.[39msignature[38;5;241m.[39mname), [1;32m 508[0m num_outputs[38;5;241m=[39m[38;5;28mself[39m[38;5;241m.[39m_num_outputs, [0;32m (...)[0m [1;32m 511[0m ctx[38;5;241m=[39mctx, [1;32m 512[0m cancellation_manager[38;5;241m=[39mcancellation_manager) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/execute.py:54[0m, in [0;36mquick_execute[0;34m(op_name, num_outputs, inputs, attrs, ctx, name)[0m [1;32m 52[0m [38;5;28;01mtry[39;00m: [1;32m 53[0m ctx[38;5;241m.[39mensure_initialized() [0;32m---> 54[0m tensors [38;5;241m=[39m [43mpywrap_tfe[49m[38;5;241;43m.[39;49m[43mTFE_Py_Execute[49m[43m([49m[43mctx[49m[38;5;241;43m.[39;49m[43m_handle[49m[43m,[49m[43m [49m[43mdevice_name[49m[43m,[49m[43m [49m[43mop_name[49m[43m,[49m [1;32m 55[0m [43m [49m[43minputs[49m[43m,[49m[43m [49m[43mattrs[49m[43m,[49m[43m [49m[43mnum_outputs[49m[43m)[49m [1;32m 56[0m [38;5;28;01mexcept[39;00m core[38;5;241m.[39m_NotOkStatusException [38;5;28;01mas[39;00m e: [1;32m 57[0m [38;5;28;01mif[39;00m name [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m: [0;31mKeyboardInterrupt[0m:
In [10]:
# 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])In [11]:
# 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 modelIn [12]:
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)In [13]:
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)In [14]:
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
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
# 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
# Change the method name to reflect which network you want to use
model = dnn2_gru2(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)
# ### 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)




















