D ANN Model 2 Demo#
Essential Libraries#
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', fontset='cm')
from typing import Tuple, Dict, List
from IPython.display import display, Latex
from sklearn.metrics import explained_variance_score, max_error, mean_absolute_error, mean_squared_error, r2_score, mean_absolute_percentage_error
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import torchvision
import torchmetrics, mlxtend
import torchinfo
from torchinfo import summary
import os
import re
import time
Set the device: cuda or cpu#
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if torch.cuda.is_available():
torch.cuda.set_device(device)
Get the data and create some useful features as extensions#
Min and max values of stellar parameters#
C_min = 0.08763469; C_max = 0.30751308;
Mbar_min = 0.909338; Mbar_max = 2.80912;
Rbar_min = 9.93864; Rbar_max = 19.4138;
x_min = 0.1406481; x_max = 0.78176399;
Ibar_min = 4.73725112; Ibar_max = 33.86946319;
D_min = 0.0046990783; D_max = 0.0335965469;
Qbar_min = 1.31339211; Qbar_max = 14.74045551;
logQbar_min = 0.27261318; logQbar_max = 2.69059579;
S3bar_min = 1.73639896; S3bar_max = 32.10634011;
min-max scaling#
min_values = np.array([C_min, x_min, logQbar_min])
max_values = np.array([C_max, x_max, logQbar_max])
# min-max scaling function
feature_scaler = lambda data: (data - min_values) / (max_values - min_values)
Input layer features: model’s input parameters#
selected_features = ['C','x','log(Qbar)']
Test subample of NS configurations#
df_test = pd.read_csv("NS_data/test_data_small_sample.csv")
df_test
| M | Req | C | x | Ibar | D | Qbar | log(Qbar) | S3bar | EoS | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2.190950 | 11.9662 | 0.270131 | 0.166659 | 5.928471 | 0.026846 | 1.935722 | 0.660480 | 3.089488 | SK272 |
| 1 | 1.348410 | 18.3103 | 0.108649 | 0.731341 | 22.361405 | 0.007117 | 7.033574 | 1.950695 | 15.180773 | SKI2 |
| 2 | 2.140930 | 15.1489 | 0.208506 | 0.552628 | 8.784199 | 0.018118 | 2.831782 | 1.040906 | 5.118462 | DD2_2 |
| 3 | 0.990131 | 13.9583 | 0.104655 | 0.387451 | 28.397753 | 0.005605 | 11.565086 | 2.447991 | 24.845141 | DS_CMF-4-Hybr |
| 4 | 1.620250 | 14.0746 | 0.169841 | 0.371895 | 12.573800 | 0.012658 | 4.981185 | 1.605668 | 9.990400 | DS_CMF-8-Hybr |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 397 | 2.200120 | 10.8028 | 0.300475 | 0.297565 | 5.216579 | 0.030509 | 1.544497 | 0.434698 | 2.207297 | BSK26 |
| 398 | 1.972780 | 16.0701 | 0.181116 | 0.655830 | 10.062797 | 0.015816 | 3.133462 | 1.142139 | 6.054977 | Rs |
| 399 | 2.033340 | 13.9065 | 0.215719 | 0.632598 | 7.410619 | 0.021477 | 2.206460 | 0.791389 | 3.821924 | KDE0v1 |
| 400 | 1.142140 | 15.3272 | 0.109939 | 0.565663 | 23.094069 | 0.006892 | 8.345383 | 2.121708 | 17.784955 | PCSB1 |
| 401 | 2.333130 | 14.6437 | 0.235064 | 0.653575 | 6.613759 | 0.024064 | 1.899356 | 0.641515 | 3.077256 | RMF3 |
402 rows × 10 columns
def load_stars(data_frame, batch_size = 2048, shuffle = True):
df_target = (data_frame['D'])
np_features = data_frame[selected_features].to_numpy()
np_targets = df_target.to_numpy()
np_targets = np.reshape(np_targets, (np_targets.shape[0], 1))
tensor_features = torch.Tensor(feature_scaler(np_features))
input_dimension = tensor_features.shape[1]
tensor_targets = torch.Tensor(np_targets)
final_dataset = TensorDataset(tensor_features, tensor_targets)
dataloader = DataLoader(final_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=5, pin_memory=True)
return dataloader, input_dimension, np_features, np_targets
Dataloader#
batch_size = 512
test_dataloader, input_dimension, _, _ = load_stars(df_test, batch_size = batch_size)
Feed-forward ANN Model to perform regression#
class RegressorModel(nn.Module):
def __init__(self,input_dimension, feature_scaler):
super().__init__()
self.feature_scaler = feature_scaler
self.MLP = nn.Sequential(
nn.Linear(input_dimension, 120),
nn.GELU(),
nn.Linear(120, 75),
nn.GELU(),
nn.Linear(75, 50),
nn.GELU(),
nn.Linear(50, 25),
nn.GELU(),
nn.Linear(25, 10),
nn.GELU(),
nn.Linear(10, 1),
)
# Initialize weights
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
nn.init.constant_(m.bias, 0.01)
def forward(self, x):
x = self.MLP(x)
return x
def predict(self, x):
x = self.feature_scaler(x).astype('float32')
x = torch.from_numpy(x).to(self.device)
x = self.MLP(x)
x = x.cpu().detach().numpy()
return x
def set_device(self, device):
self.device = device
model_0 = RegressorModel(input_dimension = input_dimension, feature_scaler = feature_scaler)
model_0
RegressorModel(
(MLP): Sequential(
(0): Linear(in_features=3, out_features=120, bias=True)
(1): GELU(approximate='none')
(2): Linear(in_features=120, out_features=75, bias=True)
(3): GELU(approximate='none')
(4): Linear(in_features=75, out_features=50, bias=True)
(5): GELU(approximate='none')
(6): Linear(in_features=50, out_features=25, bias=True)
(7): GELU(approximate='none')
(8): Linear(in_features=25, out_features=10, bias=True)
(9): GELU(approximate='none')
(10): Linear(in_features=10, out_features=1, bias=True)
)
)
summary(model_0)
=================================================================
Layer (type:depth-idx) Param #
=================================================================
RegressorModel --
├─Sequential: 1-1 --
│ └─Linear: 2-1 480
│ └─GELU: 2-2 --
│ └─Linear: 2-3 9,075
│ └─GELU: 2-4 --
│ └─Linear: 2-5 3,800
│ └─GELU: 2-6 --
│ └─Linear: 2-7 1,275
│ └─GELU: 2-8 --
│ └─Linear: 2-9 260
│ └─GELU: 2-10 --
│ └─Linear: 2-11 11
=================================================================
Total params: 14,901
Trainable params: 14,901
Non-trainable params: 0
=================================================================
ANN Model evaluation#
Load the trained Model best weights \(\theta^\star\)#
batch_size = 512
model_path = './Model-Weights/D_inference/model_2.pth'
dataloader_test, _, np_features_test, np_targets_test = load_stars(df_test, batch_size=batch_size)
regressor = RegressorModel(input_dimension = input_dimension, feature_scaler = feature_scaler).to(device)
regressor.set_device(device)
regressor.load_state_dict(torch.load(model_path, map_location=torch.device(device)))
regressor.eval()
RegressorModel(
(MLP): Sequential(
(0): Linear(in_features=3, out_features=120, bias=True)
(1): GELU(approximate='none')
(2): Linear(in_features=120, out_features=75, bias=True)
(3): GELU(approximate='none')
(4): Linear(in_features=75, out_features=50, bias=True)
(5): GELU(approximate='none')
(6): Linear(in_features=50, out_features=25, bias=True)
(7): GELU(approximate='none')
(8): Linear(in_features=25, out_features=10, bias=True)
(9): GELU(approximate='none')
(10): Linear(in_features=10, out_features=1, bias=True)
)
)
Residual Error - Fractional difference - Evaluation Measures#
def plot_residuals(residual_error, percentage_error):
witdh, height = 16, 6
fontsize = 20
labelsize = 15
lw = 5
fig, ax = plt.subplots(1, 2, figsize=(witdh, height))
# Residual error subplot
ax[0].plot(residual_error, lw=lw)
ax[0].set_xlabel(r'Datapoints', fontsize=fontsize)
ax[0].set_ylabel(r'Residual', fontsize=fontsize)
ax[0].tick_params(axis='both', which='both', labelsize=labelsize)
# Percentage error subplot
ax[1].plot(percentage_error, lw=lw)
ax[1].set_xlabel(r'Datapoints', fontsize=fontsize)
ax[1].set_ylabel(r'$PE \ [\%]$', fontsize=fontsize)
ax[1].tick_params(axis='both', which='both', labelsize=labelsize)
plt.tight_layout()
plt.show()
fig, ax = plt.subplots(1, 2, figsize=(16, 6))
fontsize = 20
labelsize = 15
lw = 5
# Residual error histogram
ax[0].hist(residual_error, bins = 20)
ax[0].set_ylabel(r'Datapoints', fontsize=fontsize)
ax[0].set_xlabel(r'Residual', fontsize=fontsize)
ax[0].tick_params(axis='both', which='both', labelsize=labelsize)
# Percentage error histogram
ax[1].hist(percentage_error, bins = 20)
ax[1].set_ylabel(r'Datapoints', fontsize=fontsize)
ax[1].set_xlabel(r'$PE \ [\%]$', fontsize=fontsize)
ax[1].tick_params(axis='both', which='both', labelsize=labelsize)
plt.tight_layout()
plt.show()
def Evaluation_Measures(y_true, y_pred):
exp_var = explained_variance_score(y_true, y_pred)
max_err = max_error(y_true, y_pred)
mae = mean_absolute_error(y_true, y_pred)
mse = mean_squared_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
mape = mean_absolute_percentage_error(y_true, y_pred)
measures = {'explained_variance': [exp_var],
'max_error': [max_err],
'mean_absolute_error': [mae],
'mean_squared_error': [mse],
'r2_score': [r2],
'mean_absolute_percentage_error': [mape]}
df_eval_measures = pd.DataFrame(measures)
return df_eval_measures
Evaluation measures in Test Set subsample#
np_targets_test = np_targets_test.ravel()
model_estimation_test_set = regressor.predict(np_features_test)
model_estimation_test_set = model_estimation_test_set.ravel().astype(np.float64)
test_eval_measures = Evaluation_Measures(y_true = np_targets_test, y_pred = model_estimation_test_set)
test_eval_measures
| explained_variance | max_error | mean_absolute_error | mean_squared_error | r2_score | mean_absolute_percentage_error | |
|---|---|---|---|---|---|---|
| 0 | 0.999948 | 0.000196 | 0.000036 | 2.413169e-09 | 0.999948 | 0.001913 |
Redidual Errors and Pecentange Errors in the test Set subsample#
residual_error_test = model_estimation_test_set - np_targets_test
percentage_error_test = (residual_error_test / np_targets_test) * 100
plot_residuals(residual_error_test, percentage_error_test)
df_test['D_model'] = model_estimation_test_set
df_test['D_model']
0 0.026845
1 0.007101
2 0.018179
3 0.005604
4 0.012640
...
397 0.030526
398 0.015751
399 0.021562
400 0.006891
401 0.024231
Name: D_model, Length: 402, dtype: float64
def D_ANN_model(x,y,w):
input_features = np.column_stack((x, y, w))
ANN_estimation = regressor.predict(input_features)
ANN_estimation = ANN_estimation.ravel().astype(np.float64)
return ANN_estimation.reshape(x.shape)
D_ANN_model(df_test['C'], df_test['x'], df_test['log(Qbar)'])
array([0.02684515, 0.00710129, 0.01817945, 0.00560361, 0.01264029,
0.0185675 , 0.01556536, 0.00840048, 0.00816241, 0.02001788,
0.01710289, 0.015199 , 0.02685622, 0.0129417 , 0.00975094,
0.01322413, 0.020949 , 0.01019705, 0.00903305, 0.01960904,
0.01418141, 0.0137535 , 0.02799466, 0.02990175, 0.02749754,
0.01054232, 0.01190199, 0.01451536, 0.02748949, 0.02188969,
0.00770937, 0.01671034, 0.00733729, 0.00963565, 0.00882688,
0.01974857, 0.01888756, 0.02201036, 0.01692744, 0.0078564 ,
0.01881349, 0.01755393, 0.01031076, 0.02690642, 0.00923249,
0.02202696, 0.02013774, 0.0080046 , 0.02157769, 0.01556509,
0.00943435, 0.01816864, 0.02143952, 0.02355035, 0.00870037,
0.02919235, 0.00817143, 0.0301838 , 0.01806923, 0.00975469,
0.02303557, 0.02310592, 0.00674477, 0.02459052, 0.02592266,
0.00753065, 0.02352708, 0.02051427, 0.01227062, 0.0285866 ,
0.0114696 , 0.00616949, 0.02966163, 0.03070258, 0.02158703,
0.02256114, 0.0097811 , 0.01852931, 0.00829778, 0.01400468,
0.02482151, 0.01610547, 0.01872578, 0.0189506 , 0.01408078,
0.0276835 , 0.0102515 , 0.02413406, 0.01355937, 0.02070484,
0.01531188, 0.02517146, 0.02522743, 0.00556967, 0.01500745,
0.010559 , 0.01634732, 0.02182689, 0.01897412, 0.01325275,
0.00998443, 0.01710181, 0.00949794, 0.0070464 , 0.02913495,
0.01839013, 0.01759794, 0.01947219, 0.00838929, 0.02804551,
0.0093562 , 0.01792453, 0.01535312, 0.02392284, 0.01649413,
0.0120888 , 0.02070221, 0.02827271, 0.02552852, 0.02298284,
0.01031297, 0.01955305, 0.02579061, 0.0131671 , 0.00790596,
0.02069554, 0.01419437, 0.01448927, 0.00872461, 0.02265056,
0.02294538, 0.01788788, 0.0124677 , 0.00858147, 0.0081475 ,
0.02537986, 0.02150489, 0.00703537, 0.02353525, 0.02604598,
0.01427267, 0.00715404, 0.00850956, 0.02966054, 0.00800671,
0.01137147, 0.02692128, 0.01602769, 0.0239715 , 0.01518457,
0.02274948, 0.02927428, 0.01120392, 0.00926026, 0.02211094,
0.01523949, 0.00596495, 0.02413569, 0.00608023, 0.01419137,
0.02148634, 0.01846475, 0.00853391, 0.02260392, 0.01675188,
0.02548341, 0.00930579, 0.02005225, 0.02798923, 0.02890682,
0.01738308, 0.0125048 , 0.01135159, 0.0187606 , 0.02538594,
0.01181442, 0.01700711, 0.00917226, 0.00915867, 0.01520122,
0.01239536, 0.00773126, 0.0235465 , 0.00718255, 0.0250604 ,
0.01438675, 0.01908887, 0.00665563, 0.01998678, 0.02847386,
0.01145517, 0.0187717 , 0.0179407 , 0.01540942, 0.02649021,
0.0089976 , 0.02557783, 0.01647216, 0.02343457, 0.01738456,
0.01816409, 0.02726322, 0.02998393, 0.01995792, 0.02434351,
0.02191362, 0.01404868, 0.01583009, 0.00609142, 0.01848499,
0.02574021, 0.01974563, 0.01974407, 0.024031 , 0.01156255,
0.02290731, 0.02456788, 0.01168766, 0.02223 , 0.03041597,
0.0200495 , 0.01312529, 0.01669426, 0.01738858, 0.00927614,
0.01568187, 0.01927477, 0.0118186 , 0.01761273, 0.02827867,
0.01023276, 0.01701699, 0.02714549, 0.02016974, 0.01576116,
0.02930758, 0.02200319, 0.02219783, 0.02164964, 0.02987493,
0.02144014, 0.02669825, 0.02283432, 0.01434516, 0.02176221,
0.02291616, 0.02246789, 0.01850025, 0.01535287, 0.01085665,
0.01983524, 0.01704891, 0.00786493, 0.01828404, 0.01003383,
0.02241964, 0.02352008, 0.017559 , 0.01539819, 0.00902312,
0.00875363, 0.01457835, 0.02072755, 0.02468988, 0.02368553,
0.00823914, 0.02620083, 0.01962206, 0.02078357, 0.02736361,
0.018716 , 0.01129674, 0.03265984, 0.02322996, 0.00932521,
0.00686048, 0.00852159, 0.01064758, 0.0118484 , 0.00933038,
0.0284786 , 0.01536143, 0.00685486, 0.01790808, 0.0289986 ,
0.02416029, 0.02226471, 0.02452362, 0.01881973, 0.02124746,
0.01841872, 0.01683485, 0.02877034, 0.02293661, 0.01590005,
0.02332577, 0.00806563, 0.01367961, 0.02799688, 0.02723116,
0.02208844, 0.02174181, 0.01674673, 0.01995124, 0.02804805,
0.02421099, 0.0111311 , 0.01473632, 0.01561041, 0.01215472,
0.00653896, 0.02171941, 0.02505864, 0.02171493, 0.01802089,
0.02945374, 0.01905283, 0.00777419, 0.02064971, 0.01060791,
0.01436313, 0.02312372, 0.00887364, 0.02159718, 0.02023228,
0.02093182, 0.02096896, 0.02573966, 0.01660364, 0.0250263 ,
0.01262883, 0.01032612, 0.02328251, 0.02366218, 0.01957142,
0.02616757, 0.03013585, 0.01378346, 0.02529052, 0.01763313,
0.02020046, 0.00809299, 0.02454746, 0.02207193, 0.00779282,
0.007056 , 0.02325857, 0.01398358, 0.01972985, 0.01543479,
0.02132009, 0.02403512, 0.01320675, 0.01095204, 0.00959815,
0.02303206, 0.02234731, 0.0075204 , 0.02785058, 0.03121058,
0.02444505, 0.00598713, 0.0184285 , 0.02025755, 0.01800852,
0.02871686, 0.02293684, 0.02177906, 0.01154724, 0.02286124,
0.00594955, 0.01829889, 0.01405004, 0.02892869, 0.00848067,
0.02915505, 0.01509347, 0.01806603, 0.02365734, 0.01172506,
0.03053275, 0.02537128, 0.01733887, 0.01929776, 0.02615923,
0.02109722, 0.01015418, 0.02114954, 0.02898146, 0.01728942,
0.01708733, 0.01426794, 0.01838046, 0.00842836, 0.02419807,
0.01373504, 0.01174638, 0.03052593, 0.01575103, 0.02156175,
0.0068913 , 0.02423129])
Model’s fractional differences associated with the test set’s subsample#
fig,ax = plt.subplots(figsize=(14, 10),)
labels_text_size = 40
plt.xticks(fontsize=30)
plt.yticks(fontsize=30)
xlabel = r'Absolute relative error [%]'
ylabel = r'Test Subsample PDF'
plt.xlabel(xlabel,size=labels_text_size)
plt.ylabel(ylabel,size=labels_text_size)
bins = 20
alpha = 0.75
density = True
y_reg_model = (np.abs(100*(-df_test['D'] + df_test['D_model'])/df_test['D'])).hist(
density=density,
bins=bins,
lw=3,
edgecolor='darkslategray',
zorder=1,
histtype='step',
alpha=alpha,
label=r"ANN model (this work)",
color='darkslategray',
).autoscale(enable=True, axis='both', tight=True)
max_deviation = (np.abs(100*(-df_test['D'] + df_test['D_model'])/df_test['D'])).max()
vertical_lines = [max_deviation]
plt.scatter(vertical_lines[0], 1.1e-2, color='darkslategray', marker='^', s=300, zorder=2, label=f'Max rel error: {np.round(max_deviation, 2)} %') # Star marker
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(3.)
plt.yscale('log')
plt.xlim(0,3)
plt.ylim(1e-2,10.2)
plt.grid(False)
leg = plt.legend(loc="upper right",ncol=1, borderaxespad=1, prop={'size': 19}, shadow=True, fontsize="large")
leg.get_frame().set_linewidth(3.0)
leg.get_frame().set_edgecolor('black')
plt.tight_layout()
plt.show()