Hyperparameter Optimization

In this tutorial we will use autoregressive approaches for virtual sensors to calculate the system response of an ESP System with external force from a shaker. This Tutorial introduces the concept of Hyperparameter optimization to find optimal parameters for our model. Please make sure to go through the basic tutorials linear_models.ipynb, ‘ARNN.ipynb and RNN.ipynb. We will start by loading the data in the same way as before.

The optimisation of hyperparameters defines a key point in the creation of deep learning models. The exact choice of hyperparameters is usually model and problem dependent, making hyperparameter optimisation necessary for most use cases.

Hyperparameters are all adjustable model and training variables that are not adjusted by a gradient-based method. In deep learning research, there is a great deal of work on optimisation. This tutorial focuses on grid search and model-based sequential optimisation.

Loading Data

In a first step we load the already measured data and convert them into pandas.DataFrames. Our example Data consists of three individually Measured datasets. To load the data properly we need information about the specific sensors. In our case we define sensors:

  • 12 input sensors

  • 3 output sensors

Furthermore, (if not given as time in the mat file) we need the corrosponsing sampling rate fs of the data.In our case:

  • fs=50000

Fixing the sampling rate will raise an Attention Message. We save the individual Measurments in a list of pandas.DataFrames

[1]:
import os
import pandas as pd
import numpy as np
data_path = os.path.join(os.path.abspath(""), 'data')

input_sensors = [f'input_{i}' for i in range(1, 10)]
output_sensors = [f'output_{i}' for i in range(1, 4)]

file_names = [f for f in os.listdir(data_path) if
                    os.path.isfile(os.path.join(data_path, f))]
df_list = [pd.read_parquet(os.path.join(data_path, n)) for n in file_names]
fs = 1/np.mean(df_list[0].index.diff().dropna())
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 11
      7 output_sensors = [f'output_{i}' for i in range(1, 4)]
      8
      9 file_names = [f for f in os.listdir(data_path) if
     10                     os.path.isfile(os.path.join(data_path, f))]
---> 11 df_list = [pd.read_parquet(os.path.join(data_path, n)) for n in file_names]
     12 fs = 1/np.mean(df_list[0].index.diff().dropna())

File ~/work/vibration-soft-sensor/vibration-soft-sensor/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:757, in read_parquet(path, engine, columns, storage_options, dtype_backend, filesystem, filters, to_pandas_kwargs, **kwargs)
    755 if engine is lib.no_default:
    756     engine = "auto"
--> 757 impl = get_engine(engine)
    758 check_dtype_backend(dtype_backend)
    760 return impl.read(
    761     path,
    762     columns=columns,
   (...)    768     **kwargs,
    769 )

File ~/work/vibration-soft-sensor/vibration-soft-sensor/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:73, in get_engine(engine)
     70         except ImportError as err:
     71             error_msgs += "\n - " + str(err)
---> 73     raise ImportError(
     74         "Unable to find a usable engine; "
     75         "tried using: 'pyarrow', 'fastparquet'.\n"
     76         "A suitable version of "
     77         "pyarrow or fastparquet is required for parquet "
     78         "support.\n"
     79         "Trying to import the above resulted in these errors:"
     80         f"{error_msgs}"
     81     )
     83 if engine == "pyarrow":
     84     return PyArrowImpl()

ImportError: Unable to find a usable engine; tried using: 'pyarrow', 'fastparquet'.
A suitable version of pyarrow or fastparquet is required for parquet support.
Trying to import the above resulted in these errors:
 - `Import pyarrow` failed. pyarrow is required for parquet support. Use pip, conda, or your preferred package management tool to install the pyarrow package.
 - `Import fastparquet` failed. fastparquet is required for parquet support. Use pip, conda, or your preferred package management tool to install the fastparquet package.

Plot the Data

Before we start with the actual preprocessing we want to plot the given data to get a feeling for the properties. These are high-frequency acceleration data recorded on a shaker. For convinience we just plot the first entry of our list of DataFrames .

[2]:
df_list[0].plot(subplots=True, sharex=True, figsize=(12,12))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 df_list[0].plot(subplots=True, sharex=True, figsize=(12,12))

NameError: name 'df_list' is not defined

Data Preprocessing

When looking at the data, the high range in which the accelerations move is striking. For many machine learning models, preprocessing is therefore necessary. Our toolbox uses the class Meas_handling for the entire preprocessing. Meas_handling is used to transform the data into a normally distributed range. Furthermore, the entire frequency range is not relevant for our analysis.

Furtehrmore we split the data in training and evaluation data. We use the first two Measurments as training and the last one as evaluation

[3]:
from softsensor.meas_handling import Meas_handling
from sklearn.preprocessing import StandardScaler

data_handle = Meas_handling(df_list[:2], file_names[:2], input_sensors, output_sensors, fs,
                            df_list[2:], file_names[2:])

data_handle.Resample(fs=10000)
freq_lim = (90, 4000)
data_handle.Filter(freq_lim)
data_handle.Scale(StandardScaler())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[3], line 4
      1 from softsensor.meas_handling import Meas_handling
      2 from sklearn.preprocessing import StandardScaler
      3
----> 4 data_handle = Meas_handling(df_list[:2], file_names[:2], input_sensors, output_sensors, fs,
      5                             df_list[2:], file_names[2:])
      6
      7 data_handle.Resample(fs=10000)

NameError: name 'df_list' is not defined

The optimisation of hyperparameters is a complex problem that requires a high computational capacity. It therefore makes sense to optimise on a GPU. Therefore, the first step is to check whether a GPU is available.

[4]:
import torch
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print('Training on', device)
Training on cpu

Visualization

We now visualise the loss over the individual hyperparameters. For 2 hyperparameters it makes sense to display them as even in the 3 dimensional space. For more parameters, other techniques such as scatter plots must be used.

[6]:
import matplotlib.pyplot as plt
from matplotlib import cm
fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(8,8))
X = result_df['lr']
stab_list = list(result_df['stabelizer'])
Y = [dic['eta'][0] for dic in stab_list]
Z = result_df['loss']
surf = ax.plot_trisurf(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)

ax.set_xlabel('lr')
ax.set_ylabel('stabelizer')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 4
      1 import matplotlib.pyplot as plt
      2 from matplotlib import cm
      3 fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(8,8))
----> 4 X = result_df['lr']
      5 stab_list = list(result_df['stabelizer'])
      6 Y = [dic['eta'][0] for dic in stab_list]
      7 Z = result_df['loss']

NameError: name 'result_df' is not defined
../_images/tutorials_04_hyperopt_11_1.png

Sequential model-based optimization

In contrast to grid search, model-based optimisation does not specify a parameter grid in advance, but only limits. The optimisation works with the so-called Tree of Parzan Estimator which samples from a space of hyperparameters. The aim is to proceed sequentially towards the optimal hyperparameters. In each case, a combination of hyperparameters is selected and then a substitute model is used to determine which combination is likely to produce the best results. Mathematically, the optimisation works with the so-called Tree of Parzan Estimator.

[7]:
from softsensor.hyperparameter_optimization import hyperopt_search
from hyperopt import hp

static_params = {'input_channels': 9,
                'pred_size': 3,
                'window_size': 50,
                'rnn_window': 50,
                'max_epochs': 2,# 30,
                'patience': 3,
                'hidden_size': [128, 64, 32, 16],
                'optimizer': 'Adam',
                'stab_method': 'const'
                }

grid_params = {'lr': hp.uniform('lr', 1e-4, 1e-2),
              's1': hp.uniform('s1', 1e-3, 1e-1)
               }

criterion = nn.MSELoss()
model_type = 'ARNN'
result_df, best_model = hyperopt_search(data_handle, criterion, model_type,
                                        static_params, grid_params, max_iterations=4,
                                        val_prediction=True, device=device, key='short',
                                        print_results=False)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 21
     17                }
     18
     19 criterion = nn.MSELoss()
     20 model_type = 'ARNN'
---> 21 result_df, best_model = hyperopt_search(data_handle, criterion, model_type,
     22                                         static_params, grid_params, max_iterations=4,
     23                                         val_prediction=True, device=device, key='short',
     24                                         print_results=False)

NameError: name 'data_handle' is not defined

Visualization

We now visualise the loss over the individual hyperparameters. For 2 hyperparameters it makes sense to display them as even in the 3 dimensional space. For more parameters, other techniques such as scatter plots must be used.

[8]:
fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(8,8))
X = result_df['lr']
stab_list = list(result_df['stabelizer'])
Y = [dic['eta'][0] for dic in stab_list]
Z = result_df['loss']
surf = ax.plot_trisurf(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)

ax.set_xlabel('lr')
ax.set_ylabel('stabelizer')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 2
      1 fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(8,8))
----> 2 X = result_df['lr']
      3 stab_list = list(result_df['stabelizer'])
      4 Y = [dic['eta'][0] for dic in stab_list]
      5 Z = result_df['loss']

NameError: name 'result_df' is not defined
../_images/tutorials_04_hyperopt_16_1.png

Model Evaluation

To Evaluate our model on testing data we use the predefined functions comp_pred, which computes the prediction for a defined track in the data_handle class. As track we choose our testing track, which can be accessed using the internal variable test_names. Furthermore we compute

[9]:
from softsensor.eval_tools import comp_pred, comp_error
from softsensor.linear_methods import tf

tf_class = tf(window_size=1024,hop=512, fs=10000)
tf_class.fit(data_handle.train_df, input_sensors, output_sensors)

track = data_handle.test_names[0]
models = [best_model, tf_class]
pred_df = comp_pred(models, data_handle, track, names=['Neural Network', 'TF'])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 5
      1 from softsensor.eval_tools import comp_pred, comp_error
      2 from softsensor.linear_methods import tf
      3
      4 tf_class = tf(window_size=1024,hop=512, fs=10000)
----> 5 tf_class.fit(data_handle.train_df, input_sensors, output_sensors)
      6
      7 track = data_handle.test_names[0]
      8 models = [best_model, tf_class]

NameError: name 'data_handle' is not defined
[10]:
pred_df.filter(regex='a_PCB_P10_A1S_Z').plot(figsize=(12,4))
pred_df.filter(regex='a_PCB_P10_A1S_Z')[1:1.02].plot(figsize=(12,4))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 pred_df.filter(regex='a_PCB_P10_A1S_Z').plot(figsize=(12,4))
      2 pred_df.filter(regex='a_PCB_P10_A1S_Z')[1:1.02].plot(figsize=(12,4))

NameError: name 'pred_df' is not defined
[11]:
error = comp_error(pred_df, output_sensors, fs, names=['Neural Network', 'TF'], metrics=['MSE', 'MAE'], freq_range=freq_lim)
for n in ['MSE', 'MAE']:
    error.filter(regex=n, axis=0).plot.bar(ylabel=f'{n}', rot=45)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 error = comp_error(pred_df, output_sensors, fs, names=['Neural Network', 'TF'], metrics=['MSE', 'MAE'], freq_range=freq_lim)
      2 for n in ['MSE', 'MAE']:
      3     error.filter(regex=n, axis=0).plot.bar(ylabel=f'{n}', rot=45)

NameError: name 'pred_df' is not defined