-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyS_ANN_PP Opt14.py
130 lines (94 loc) · 4.26 KB
/
PyS_ANN_PP Opt14.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# -*- coding: utf-8 -*-
"""Artificial Neural Network
# This code is generated by Dr. Kazi Monzure Khoda
### Importing the libraries
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from sklearn.metrics import mean_squared_error
from keras.callbacks import EarlyStopping
import pysindy as ps
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import r2_score
from sklearn.model_selection import ShuffleSplit
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import Lasso
tf.__version__
"""## Part 1 - Data Preprocessing
### Importing the dataset
"""
dataset = pd.read_excel('PP Load 2.xlsx')
datasetTest = pd.read_excel('X_given_PP14.xlsx')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
X_given=datasetTest.iloc[:, :-1].values
# # Taking care of missing data
# from sklearn.impute import SimpleImputer
# imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
# imputer = imputer.fit(X[:, 0:7])
# X[:, 0:7] = imputer.transform(X[:, 0:7])
"""### Splitting the dataset into the Training set and Test set"""
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)
## Part 2 - Building the ANN
ann = tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units=300, activation='relu', input_dim = 3))
ann.add(tf.keras.layers.Dense(units=300, activation='relu'))
ann.add(tf.keras.layers.Dense(units=300, activation='relu'))
ann.add(tf.keras.layers.Dense(units=300, activation='relu'))
#ann.add(tf.keras.layers.Dense(units=300, activation='relu'))
ann.add(tf.keras.layers.Dense(units=1))
ann.compile(optimizer = 'adam', loss = 'mean_squared_error')
"""### Training the ANN model on the Training set"""
#ann.fit(X_train, y_train, batch_size = 32, epochs = 10000)
"""### Training the ANN model on the Training set"""
early_stopping_monitor = EarlyStopping(monitor='val_loss', patience=5000) # ignored
history_mse = ann.fit(X_train, y_train, batch_size = 32, epochs = 20000, callbacks = [early_stopping_monitor], verbose = 0, validation_split = 0.2)
print('Loss: ', history_mse.history['loss'][-1], '\nVal_loss: ', history_mse.history['val_loss'][-1])
# EVALUATE MODEL IN THE TEST SET
score_mse_test = ann.evaluate(X_test, y_test)
print('Test Score:', score_mse_test)
# EVALUATE MODEL IN THE TRAIN SET
score_mse_train = ann.evaluate(X_train, y_train)
print('Train Score:', score_mse_train)
#batch seize 32 is working better
ann.save('my_model_PP14PyS5')
"""### Predicting the results of the Test set"""
# y_pred = ann.predict(np.array([[0.07, 0.06, .139, 0.765, 28, 440, 15.7, 0.1390, 39.6 ]]))
#y_pred = ann.predict(np.array([[12.95, 0.35, 13.30, 0.8, 35.8, 700, 20, 30 ]]))
y_pred = ann.predict(X_given)
#model = ps.SINDy(optimizer=ps.STLSQ(threshold=.02, alpha=.05),feature_library=ps.PolynomialLibrary(), t_default=1)
#model = ps.SINDy(t_default=1) # cross validatin 2nd without split KMK
xt = (X_given[:,2].reshape(len(X_given),))
yst = ((y_pred).reshape(len(y_pred),))
Xt = np.stack((xt, yst), axis=-1)
#lasso_optimizer = Lasso(alpha=2, max_iter=2000, fit_intercept=False)
#model = ps.SINDy(optimizer=lasso_optimizer)
model = ps.SINDy(optimizer=ps.STLSQ(threshold=.00002, alpha=.05),feature_library=ps.PolynomialLibrary(), t_default=1)
model.fit(Xt)
model.print()
c= model.coefficients()
ms = model.score(Xt)
fig = plt.figure(figsize=(12,6))
#plt.figure(figsize=(15, 6))
#ax = fig.add_subplot(211)
plt.plot(history_mse.history['loss'], lw =3, ls = '--', label = 'Loss')
plt.plot(history_mse.history['val_loss'], lw =2, ls = '-', label = 'Val Loss')
plt.xlabel('Epochs', fontsize=15)
plt.ylabel('Loss', fontsize=15)
plt.title('MSE')
plt.legend()
plt.show()
fig = plt.figure(figsize=(10,6))
plt.plot(X[107:200,2], y[107:200],color='green', linestyle='dashed', label = 'Experimental curve for 10%')
plt.plot(X[201:294,2], y[201:294], color = 'red', linestyle='dashed', label = 'Experimental curve for 20%')
plt.plot( X_given[:,2],y_pred, color = 'blue', label = 'ANN prediction for 14%')
plt.title('Predicted load-displacement curve for optimum fiber content')
plt.xlabel('Displacement (mm)')
plt.ylabel('Load (kN)')
plt.legend()
plt.show()