24 """ Constructor of the state object """
32 for key, value
in kwargs.items():
34 setattr(self, key, value)
37def feature_importance(state):
39 Return a list containing the feature importances.
40 Torch does not provide feature importances so
return an empty list.
47 My dense neural network
53 param: number_of_features number of input variables
59 torch.nn.Linear(number_of_features, 128),
61 torch.nn.Linear(128, 128),
63 torch.nn.Linear(128, 1),
75def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
77 Returns default torch model
83 if parameters
is None:
86 state.optimizer = torch.optim.SGD(state.model.parameters(), parameters.get(
'learning_rate', 1e-3))
90 state.loss_fn = torch.nn.BCELoss
95def begin_fit(state, Xtest, Stest, ytest, wtest, nBatches):
97 Passes in a fraction of events
if specific_options.m_training_fraction
is set.
101 state.Xtest = torch.from_numpy(Xtest).to(device)
102 state.ytest = torch.from_numpy(ytest).to(device)
103 state.wtest = torch.from_numpy(wtest).to(device)
107def partial_fit(state, X, S, y, w, epoch, batch):
109 Pass received data to the torch model and train.
111 The epochs
and batching are handled by the mva package.
112 If you prefer to do this yourself set
113 specific_options.m_nIterations = 1
114 specific_options.m_mini_batch_size = 0
115 which will
pass all training data
as a single batch once.
116 This can then be loaded into torch
in any way you want.
120 tensor_x = torch.from_numpy(X).to(device)
121 tensor_y = torch.from_numpy(y).to(device).type(torch.float)
122 tensor_w = torch.from_numpy(w).to(device)
125 loss_fn = state.loss_fn(weight=tensor_w)
126 pred = state.model(tensor_x)
127 loss = loss_fn(pred, tensor_y)
130 state.optimizer.zero_grad()
132 state.optimizer.step()
134 if batch == 0
and epoch == 0:
135 state.avg_costs = [loss.detach().numpy()]
137 elif epoch != state.epoch:
139 if len(state.ytest) > 0:
142 with torch.no_grad():
143 test_pred = state.model(state.Xtest)
144 test_loss_fn = state.loss_fn(weight=state.wtest)
145 test_loss = test_loss_fn(test_pred, state.ytest).item()
146 test_correct = (test_pred.round() == state.ytest).type(torch.float).sum().item()
148 print(f
"Epoch: {epoch-1:04d},\t Training Cost: {np.mean((state.avg_costs)):.4f},"
149 f
"\t Testing Cost: {test_loss:.4f}, \t Testing Accuracy: {test_correct/len(state.ytest)}")
152 print(f
"Epoch: {epoch-1:04d},\t Training Cost: {np.mean((state.avg_costs)):.4f}")
154 state.avg_costs = [loss.detach().numpy()]
157 state.avg_costs.append(loss.detach().numpy())
166 Apply estimator to passed data.
168 with torch.no_grad():
169 r = state.model(torch.from_numpy(X)).detach().numpy()
172 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
177 Load the trained torch model into state.
179 with tempfile.TemporaryDirectory()
as temp_path:
180 temp_path = pathlib.Path(temp_path)
183 for file_index, file_name
in enumerate(file_names):
184 path = temp_path.joinpath(pathlib.Path(file_name))
185 path.parents[0].mkdir(parents=
True, exist_ok=
True)
187 with open(path,
'w+b')
as file:
188 file.write(bytes(obj[1][file_index]))
193 model = torch.load(temp_path.joinpath(file_names[0]))
200 for index, key
in enumerate(obj[2]):
201 setattr(state, key, obj[3][index])
209 with tempfile.TemporaryDirectory()
as temp_path:
211 temp_path = pathlib.Path(temp_path)
215 torch.save(state.model, temp_path.joinpath(
'my_model.pt'))
217 file_names = [
'my_model.pt']
219 for file_name
in file_names:
220 with open(temp_path.joinpath(file_name),
'rb')
as file:
221 files.append(file.read())
223 collection_keys = state.collection_keys
224 collections_to_store = []
225 for key
in state.collection_keys:
226 collections_to_store.append(getattr(state, key))
229 return [file_names, files, collection_keys, collections_to_store]
collection_keys
list of keys to save.
def __init__(self, model=None, **kwargs)
network
a dense model with one hidden layer
def __init__(self, number_of_features)