OpenNN
Open-source neural networks library
Loading...
Searching...
No Matches
loss.h
Go to the documentation of this file.
1// OpenNN: Open Neural Networks Library
2// www.opennn.net
3//
4// L O S S I N D E X C L A S S H E A D E R
5//
6// Artificial Intelligence Techniques SL
7// artelnics@artelnics.com
8
9#pragma once
10
11#include "neural_network.h"
12#include "back_propagation.h"
13
14namespace opennn
15{
16
17class Dataset;
18
19struct Batch;
21
23class Loss
24{
25
26public:
27
35
38
41 {
42 static const vector<pair<Regularization, string>> entries = {
44 {Regularization::L1, "L1"},
45 {Regularization::L2, "L2"},
46 {Regularization::ElasticNet, "ElasticNet"}
47 };
48 static const EnumMap<Regularization> map{entries};
49 return map;
50 }
51
53 static const string& regularization_to_string(Regularization regularization)
54 {
55 return regularization_map().to_string(regularization);
56 }
57
60 {
61 if (name == "NoRegularization") return Regularization::NoRegularization;
62 return regularization_map().from_string(name);
63 }
64
68 Loss(NeuralNetwork* = nullptr, Dataset* = nullptr);
69
70 virtual ~Loss() = default;
71
73 {
74 return neural_network;
75 }
76
81
82 const Dataset* get_dataset() const
83 {
84 return dataset;
85 }
86
88 {
89 return dataset;
90 }
91
93 void set(NeuralNetwork* = nullptr, Dataset* = nullptr);
94
95 void set_neural_network(NeuralNetwork* new_neural_network) { neural_network = new_neural_network; }
96
97 virtual void set_dataset(Dataset* new_dataset) { dataset = new_dataset; }
98
99 void set_regularization(const string& new_regularization_method) { regularization_method = string_to_regularization(new_regularization_method); }
100 void set_regularization(Regularization new_regularization) { regularization_method = new_regularization; }
101 void set_regularization_weight(const float new_regularization_weight) { regularization_weight = new_regularization_weight; }
102
105
108 {
109 float error = 0.0f;
110 float accuracy = 0.0f;
112 };
113
119 const ForwardPropagation&) const;
120
122 void set_error(const Error&);
124 void set_error(const string&);
125
126 Error get_error() const { return error; }
127
134 BackPropagation&) const;
135
136#ifdef OPENNN_HAS_CUDA
138 bool supports_device_epoch_metrics() const;
139
141 bool back_propagate_device_metrics(const Batch&,
144 float* error_sum_device,
145 float* accuracy_sum_device) const;
146
148 bool calculate_error_device_metrics(const Batch&,
149 const ForwardPropagation&,
150 float* error_sum_device,
151 float* accuracy_sum_device) const;
152#endif
153
158
160 void to_JSON(JsonWriter&) const;
161
166
167 const string& get_name() const { return name; }
169 static float calculate_h(const float);
170
172 void print() const {}
173
174private:
175
176 void check_neural_network() const
177 {
178 if (!neural_network)
179 throw runtime_error("Loss error: neural network is not set.");
180 }
181
182 void check_dataset() const
183 {
184 if (!dataset)
185 throw runtime_error("Loss error: dataset is not set.");
186 }
187
188 void add_regularization(BackPropagation&) const;
189
190 float get_weighted_coefficient(const Batch&) const;
191
192 void calculate_layers_error_gradient(const Batch&,
193 ForwardPropagation&,
194 BackPropagation&) const;
195
196 void back_propagate_layers(ForwardPropagation&,
197 BackPropagation&) const;
198
199 void add_regularization_gradient(BackPropagation&) const;
200
201 void calculate_output_deltas(const Batch&,
202 const ForwardPropagation&,
203 BackPropagation&) const;
204
205protected:
206
208
209 // Method-specific parameters
211 float positives_weight = 1.0f;
212 float negatives_weight = 1.0f;
214
215#ifdef OPENNN_HAS_CUDA
216 // Reduction workspace for cublasSasum/cudaMemcpy used by the loss kernels.
217 // mutable because calculate_error grows it lazily on the first call; the
218 // method's logical contract is still const (no observable state changes).
219 mutable Buffer errors_device{Device::CUDA};
220 mutable Buffer metric_results_device{Device::CUDA};
221#endif
222
223 // Regularization
225 float regularization_weight = 0.001f;
226
228 Dataset* dataset = nullptr;
229
230 string name = "Loss";
231};
232
233}
234
235// OpenNN: Open Neural Networks Library.
236// Copyright(C) 2005-2026 Artificial Intelligence Techniques, SL.
237// Licensed under the GNU Lesser General Public License v2.1 or later.
Abstract base class for OpenNN datasets, owning samples, variables, and metadata.
Definition dataset.h:61
Definition json.h:72
Definition json.h:85
static Regularization string_to_regularization(const string &name)
Parses a regularization name (accepts both "NoRegularization" and "None") back to the enum.
Definition loss.h:59
float negatives_weight
Definition loss.h:212
float normalization_coefficient
Definition loss.h:210
NeuralNetwork * get_neural_network()
Definition loss.h:77
NeuralNetwork * neural_network
Definition loss.h:227
Regularization regularization_method
Definition loss.h:224
float calculate_regularization(const VectorR &) const
Returns the regularization penalty (L1, L2, or ElasticNet) for the given parameter vector.
float positives_weight
Definition loss.h:211
void set_regularization(const string &new_regularization_method)
Definition loss.h:99
void from_JSON(const JsonDocument &)
Restores loss configuration (error type, regularization, weights) from a JSON document.
void regularization_from_JSON(const JsonDocument &)
Restores the regularization sub-configuration from JSON.
static float calculate_h(const float)
Returns the finite-difference step size h tuned for the given parameter value.
Dataset * get_dataset()
Definition loss.h:87
static const string & regularization_to_string(Regularization regularization)
Returns the canonical string name for a Regularization value.
Definition loss.h:53
Error error
Definition loss.h:207
void print() const
Prints a human-readable description of the loss (no-op default).
Definition loss.h:172
float regularization_weight
Definition loss.h:225
Dataset * dataset
Definition loss.h:228
virtual void set_dataset(Dataset *new_dataset)
Definition loss.h:97
void set(NeuralNetwork *=nullptr, Dataset *=nullptr)
Resets the bound neural network and dataset pointers.
void set_normalization_coefficient()
Recomputes the normalization coefficient (used by NormalizedSquaredError) from the dataset.
void regularization_to_JSON(JsonWriter &) const
Serializes the regularization sub-configuration to JSON.
string name
Definition loss.h:230
static const EnumMap< Regularization > & regularization_map()
Returns the static string<->enum map used to (de)serialize regularization types.
Definition loss.h:40
void back_propagate(const Batch &, ForwardPropagation &, BackPropagation &) const
Performs the full backward pass: output deltas, layer gradients, and regularization gradient.
void set_error(const string &)
Selects the error function variant from its string name.
void set_neural_network(NeuralNetwork *new_neural_network)
Definition loss.h:95
EvaluationResult calculate_error(const Batch &, const ForwardPropagation &) const
Computes the loss for one batch using the cached forward-pass outputs.
void to_JSON(JsonWriter &) const
Serializes the loss configuration (error type, regularization, weights) to JSON.
Error get_error() const
Definition loss.h:126
Loss(NeuralNetwork *=nullptr, Dataset *=nullptr)
Constructs a Loss bound to an optional neural network and dataset.
Regularization
Parameter regularization method applied on top of the base loss.
Definition loss.h:37
@ NoRegularization
Definition loss.h:37
@ L2
Definition loss.h:37
@ L1
Definition loss.h:37
@ ElasticNet
Definition loss.h:37
const string & get_name() const
Definition loss.h:167
void set_error(const Error &)
Selects the error function variant.
virtual ~Loss()=default
const Dataset * get_dataset() const
Definition loss.h:82
void set_regularization_weight(const float new_regularization_weight)
Definition loss.h:101
Error
Error function selector used to dispatch the loss kernel.
Definition loss.h:29
@ CrossEntropy3d
Definition loss.h:33
@ CrossEntropy
Definition loss.h:32
@ MinkowskiError
Definition loss.h:34
@ NormalizedSquaredError
Definition loss.h:30
@ MeanSquaredError
Definition loss.h:29
@ WeightedSquaredError
Definition loss.h:31
float minkowski_parameter
Definition loss.h:213
void set_regularization(Regularization new_regularization)
Definition loss.h:100
const NeuralNetwork * get_neural_network() const
Definition loss.h:72
Container of layers forming a feed-forward neural network, with parameter storage and I/O.
Definition neural_network.h:20
Definition adaptive_moment_estimation.h:14
@ CUDA
Definition configuration.h:17
Matrix< float, Dynamic, 1 > VectorR
Definition pch.h:181
Workspace holding parameter gradients and per-layer deltas during a backward pass.
Definition back_propagation.h:21
Minibatch container holding pinned host/device buffers and views into a Dataset.
Definition batch.h:19
Owning raw byte buffer that lives on CPU or CUDA memory, with aligned (re)allocation.
Definition tensor_utilities.h:166
Definition enum_map.h:18
Workspace holding the activations of every layer during a forward pass.
Definition forward_propagation.h:20
Result of calculate_error; accuracy and active_tokens_count are populated only by classification loss...
Definition loss.h:108
float accuracy
Definition loss.h:110
Index active_tokens_count
Definition loss.h:111
float error
Definition loss.h:109