Skip to content

Commit 5892799

Browse files
0.10.8
introducing verbosity
1 parent 9d842a3 commit 5892799

5 files changed

Lines changed: 28 additions & 53 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
77

88
[project]
99
name = "spotPython"
10-
version = "0.10.7"
10+
version = "0.10.8"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotPython/data/lightdatamodule.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,6 @@ def train_dataloader(self) -> DataLoader:
121121
print(f"LightDataModule: train_dataloader(). Training set size: {len(self.data_train)}")
122122
print(f"LightDataModule: train_dataloader(). batch_size: {self.batch_size}")
123123
print(f"LightDataModule: train_dataloader(). num_workers: {self.num_workers}")
124-
print("Calling DataLoader()")
125124
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers)
126125

127126
def val_dataloader(self) -> DataLoader:
@@ -164,4 +163,7 @@ def test_dataloader(self) -> DataLoader:
164163
Test set size: 6
165164
166165
"""
166+
print(f"LightDataModule: test_dataloader(). Training set size: {len(self.data_test)}")
167+
print(f"LightDataModule: test_dataloader(). batch_size: {self.batch_size}")
168+
print(f"LightDataModule: test_dataloader(). num_workers: {self.num_workers}")
167169
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers)

src/spotPython/fun/hyperlight.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import numpy as np
3+
import pprint
34
from numpy.random import default_rng
45
from spotPython.light.trainmodel import train_model
56
from spotPython.hyperparameters.values import assign_values, generate_one_config_from_var_dict, get_var_name
@@ -132,6 +133,9 @@ def fun(self, X: np.ndarray, fun_control: dict = None) -> np.ndarray:
132133
var_dict = assign_values(X, get_var_name(fun_control))
133134
# type information and transformations are considered in generate_one_config_from_var_dict:
134135
for config in generate_one_config_from_var_dict(var_dict, fun_control):
136+
if fun_control["verbosity"] > 0:
137+
print("\nIn fun(): config:")
138+
pprint.pprint(config)
135139
logger.debug(f"\nconfig: {config}")
136140
# extract parameters like epochs, batch_size, lr, etc. from config
137141
# config_id = generate_config_id(config)
@@ -140,6 +144,10 @@ def fun(self, X: np.ndarray, fun_control: dict = None) -> np.ndarray:
140144
df_eval = train_model(config, fun_control)
141145
logger.debug("fun: train_model returned")
142146
except Exception as err:
147+
if fun_control["verbosity"] > 0:
148+
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
149+
print(f"Error in fun(). Call to train_model failed. {err=}, {type(err)=}")
150+
print("Setting df_eval to np.nan\n")
143151
logger.error(f"Error in fun(). Call to train_model failed. {err=}, {type(err)=}")
144152
logger.error("Setting df_eval to np.nan")
145153
df_eval = np.nan

src/spotPython/light/regression/rnnlightregression.py

Lines changed: 11 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -170,34 +170,15 @@ def __init__(
170170
# self.dropout1 = nn.Dropout(dropout[0])
171171
# self.dropout2 = nn.Dropout(dropout[1])
172172
# self.dropout3 = nn.Dropout(dropout[2])
173-
# # TODO: use different dropout for different layers
173+
# # TODO: use enhanced dropout management for different layers
174174
self.dropout1 = nn.Dropout(self.hparams.dropout_prob)
175175
self.dropout2 = nn.Dropout(self.hparams.dropout_prob // 10.0)
176176
self.dropout3 = nn.Dropout(self.hparams.dropout_prob // 100.0)
177177

178-
activation_fct = nn.ReLU()
179-
self.activation_fct = activation_fct
180-
# self.activation_fct = self.hparams.act_fn
181-
182-
# ###########################################
183-
# old:
184-
# if self.hparams.l1 < 4:
185-
# raise ValueError("l1 must be at least 4")
186-
# hidden_sizes = [self.hparams.l1, self.hparams.l1 // 2, self.hparams.l1 // 2, self.hparams.l1 // 4]
187-
# Create the network based on the specified hidden sizes
188-
# layers = []
189-
# layer_sizes = [self._L_in] + hidden_sizes
190-
# layer_size_last = layer_sizes[0]
191-
# for layer_size in layer_sizes[1:]:
192-
# layers += [
193-
# nn.Linear(layer_size_last, layer_size),
194-
# self.hparams.act_fn,
195-
# nn.Dropout(self.hparams.dropout_prob),
196-
# ]
197-
# layer_size_last = layer_size
198-
# layers += [nn.Linear(layer_sizes[-1], self._L_out)]
199-
# # nn.Sequential summarizes a list of modules into a single module, applying them in sequence
200-
# self.layers = nn.Sequential(*layers)
178+
# TODO: Enable different activation functions
179+
# activation_fct = nn.ReLU()
180+
# self.activation_fct = activation_fct
181+
self.activation_fct = self.hparams.act_fn
201182

202183
def forward(self, x: torch.Tensor) -> torch.Tensor:
203184
"""
@@ -227,22 +208,13 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
227208
# print(f"output_layer: {x.shape}")
228209
return x
229210

230-
# old:
231-
# x = self.layers(x)
232-
# # check if the number of columns in x is 1, otherwise throw an error
233-
# try:
234-
# assert x.shape[1] == 1
235-
# except AssertionError:
236-
# print(f"forward x.shape: {x.shape}")
237-
# raise AssertionError("Number of columns in x is not 1.")
238-
# return x
239-
240-
def training_step(self, batch: tuple) -> torch.Tensor:
211+
def training_step(self, batch: tuple, prog_bar: bool = False) -> torch.Tensor:
241212
"""
242213
Performs a single training step.
243214
244215
Args:
245216
batch (tuple): A tuple containing a batch of input data and labels.
217+
prog_bar (bool, optional): Whether to display the progress bar. Defaults to False.
246218
247219
Returns:
248220
torch.Tensor: A tensor containing the loss for this batch.
@@ -251,26 +223,14 @@ def training_step(self, batch: tuple) -> torch.Tensor:
251223
x, y = batch
252224
# reshape the tensor y to be a column vector (len(y) rows and 1 column)
253225
y = y.view(len(y), 1)
254-
# check if the number of rows in x is equal to the number of rows in y, otherwise throw an error
255-
try:
256-
assert x.shape[0] == y.shape[0]
257-
except AssertionError:
258-
print(f"training_step x.shape: {x.shape}")
259-
print(f"training_step y.shape: {y.shape}")
260-
raise AssertionError("Number of rows in x and y must be equal")
226+
# Note: the number of rows in x is equal to the number of rows in y
261227
y_hat = self(x)
262-
# check if the number of rows in y_hat is equal to the number of rows in y, otherwise throw an error
263-
try:
264-
assert y_hat.shape[0] == y.shape[0]
265-
except AssertionError:
266-
print(f"training_step y_hat.shape: {y_hat.shape}")
267-
print(f"training_step y.shape: {y.shape}")
268-
raise AssertionError("Number of rows in y_hat and y must be equal")
269-
val_loss = F.mse_loss(y_hat, y)
228+
# Note: the number of rows in y_hat is equal to the number of rows in y
229+
train_loss = F.mse_loss(y_hat, y)
270230
# mae_loss = F.l1_loss(y_hat, y)
271231
# self.log("train_loss", val_loss, on_step=True, on_epoch=True, prog_bar=True)
272232
# self.log("train_mae_loss", mae_loss, on_step=True, on_epoch=True, prog_bar=True)
273-
return val_loss
233+
return train_loss
274234

275235
def validation_step(self, batch: tuple, batch_idx: int, prog_bar: bool = False) -> torch.Tensor:
276236
"""

src/spotPython/utils/init.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ def fun_control_init(
4242
upper=None,
4343
var_name=None,
4444
var_type=["num"],
45+
verbosity=0,
4546
):
4647
"""Initialize fun_control dictionary.
4748
Args:
@@ -133,6 +134,9 @@ def fun_control_init(
133134
var_type (List[str]):
134135
list of type information, can be either "int", "num" or "factor".
135136
Default is ["num"].
137+
verbosity (int):
138+
The verbosity level. Determines print output to console. Higher values
139+
result in more output. Default is 0.
136140
137141
Returns:
138142
fun_control (dict):
@@ -282,6 +286,7 @@ def fun_control_init(
282286
"upper": upper,
283287
"var_name": var_name,
284288
"var_type": var_type,
289+
"verbosity": verbosity,
285290
"weights": 1.0,
286291
}
287292
# lower = X_reshape(lower)

0 commit comments

Comments
 (0)