From 06db8f51cec69c664fc9b4e891f57af199683aef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Monta=C3=B1ana?= Date: Mon, 7 Aug 2023 12:49:37 +0200 Subject: [PATCH 1/6] Refactor library and models to lighten data stored Refactro Ensemble to inherit from Classifier insted of BaseClassifier --- src/BayesNet/AODE.cc | 2 +- src/BayesNet/AODE.h | 2 +- src/BayesNet/AODELd.cc | 16 ++++++---- src/BayesNet/AODELd.h | 4 ++- src/BayesNet/BaseClassifier.h | 1 + src/BayesNet/BayesMetrics.cc | 10 +++--- src/BayesNet/BayesMetrics.h | 10 +++--- src/BayesNet/Classifier.cc | 60 ++++++++++++++++------------------- src/BayesNet/Classifier.h | 14 ++++---- src/BayesNet/Ensemble.cc | 50 +++-------------------------- src/BayesNet/Ensemble.h | 17 ++-------- src/BayesNet/KDB.cc | 5 +-- src/BayesNet/KDB.h | 2 +- src/BayesNet/KDBLd.cc | 9 ++---- src/BayesNet/Mst.cc | 2 +- src/BayesNet/Mst.h | 2 +- src/BayesNet/Network.cc | 26 +++++++-------- src/BayesNet/Network.h | 6 ++-- src/BayesNet/Node.cc | 20 +++++++++--- src/BayesNet/Node.h | 2 +- src/BayesNet/Proposal.cc | 22 ++++++------- src/BayesNet/Proposal.h | 9 +++--- src/BayesNet/SPODE.cc | 2 +- src/BayesNet/SPODE.h | 2 +- src/BayesNet/SPODELd.cc | 10 ++---- src/BayesNet/TAN.cc | 6 ++-- src/BayesNet/TAN.h | 2 +- src/BayesNet/TANLd.cc | 10 ++---- 28 files changed, 134 insertions(+), 189 deletions(-) diff --git a/src/BayesNet/AODE.cc b/src/BayesNet/AODE.cc index 6ec9361..66c71da 100644 --- a/src/BayesNet/AODE.cc +++ b/src/BayesNet/AODE.cc @@ -2,7 +2,7 @@ namespace bayesnet { AODE::AODE() : Ensemble() {} - void AODE::train() + void AODE::buildModel() { models.clear(); for (int i = 0; i < features.size(); ++i) { diff --git a/src/BayesNet/AODE.h b/src/BayesNet/AODE.h index 9a698e1..5447fc0 100644 --- a/src/BayesNet/AODE.h +++ b/src/BayesNet/AODE.h @@ -5,7 +5,7 @@ namespace bayesnet { class AODE : public Ensemble { protected: - void train() override; + void buildModel() override; public: AODE(); virtual ~AODE() {}; diff --git a/src/BayesNet/AODELd.cc b/src/BayesNet/AODELd.cc index 861aa71..18e3761 100644 --- a/src/BayesNet/AODELd.cc +++ b/src/BayesNet/AODELd.cc @@ -2,27 +2,31 @@ namespace bayesnet { using namespace std; - AODELd::AODELd() : Ensemble(), Proposal(Ensemble::Xv, Ensemble::yv, features, className) {} + AODELd::AODELd() : Ensemble(), Proposal(dataset, features, className) {} AODELd& AODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { features = features_; className = className_; states = states_; - train(); - for (const auto& model : models) { - model->fit(X_, y_, features_, className_, states_); - } + buildModel(); + trainModel(); n_models = models.size(); fitted = true; return *this; } - void AODELd::train() + void AODELd::buildModel() { models.clear(); for (int i = 0; i < features.size(); ++i) { models.push_back(std::make_unique(i)); } } + void AODELd::trainModel() + { + for (const auto& model : models) { + model->fit(dataset, features, className, states); + } + } Tensor AODELd::predict(Tensor& X) { return Ensemble::predict(X); diff --git a/src/BayesNet/AODELd.h b/src/BayesNet/AODELd.h index 33a0dff..c8db41d 100644 --- a/src/BayesNet/AODELd.h +++ b/src/BayesNet/AODELd.h @@ -7,13 +7,15 @@ namespace bayesnet { using namespace std; class AODELd : public Ensemble, public Proposal { + private: + void trainModel(); + void buildModel() override; public: AODELd(); virtual ~AODELd() = default; AODELd& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; vector graph(const string& name = "AODE") override; Tensor predict(Tensor& X) override; - void train() override; static inline string version() { return "0.0.1"; }; }; } diff --git a/src/BayesNet/BaseClassifier.h b/src/BayesNet/BaseClassifier.h index 0ae9a1d..e95fafc 100644 --- a/src/BayesNet/BaseClassifier.h +++ b/src/BayesNet/BaseClassifier.h @@ -10,6 +10,7 @@ namespace bayesnet { virtual BaseClassifier& fit(vector>& X, vector& y, vector& features, string className, map>& states) = 0; // X is nxm tensor, y is nx1 tensor virtual BaseClassifier& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) = 0; + virtual BaseClassifier& fit(torch::Tensor& dataset, vector& features, string className, map>& states) = 0; virtual ~BaseClassifier() = default; torch::Tensor virtual predict(torch::Tensor& X) = 0; vector virtual predict(vector>& X) = 0; diff --git a/src/BayesNet/BayesMetrics.cc b/src/BayesNet/BayesMetrics.cc index c80fb65..8952ead 100644 --- a/src/BayesNet/BayesMetrics.cc +++ b/src/BayesNet/BayesMetrics.cc @@ -2,7 +2,7 @@ #include "Mst.h" namespace bayesnet { //samples is nxm tensor used to fit the model - Metrics::Metrics(torch::Tensor& samples, vector& features, string& className, int classNumStates) + Metrics::Metrics(const torch::Tensor& samples, const vector& features, const string& className, const int classNumStates) : samples(samples) , features(features) , className(className) @@ -76,7 +76,7 @@ namespace bayesnet { std::vector v(matrix.data_ptr(), matrix.data_ptr() + matrix.numel()); return v; } - double Metrics::entropy(torch::Tensor& feature) + double Metrics::entropy(const torch::Tensor& feature) { torch::Tensor counts = feature.bincount(); int totalWeight = counts.sum().item(); @@ -86,7 +86,7 @@ namespace bayesnet { return entropy.nansum().item(); } // H(Y|X) = sum_{x in X} p(x) H(Y|X=x) - double Metrics::conditionalEntropy(torch::Tensor& firstFeature, torch::Tensor& secondFeature) + double Metrics::conditionalEntropy(const torch::Tensor& firstFeature, const torch::Tensor& secondFeature) { int numSamples = firstFeature.sizes()[0]; torch::Tensor featureCounts = secondFeature.bincount(); @@ -115,7 +115,7 @@ namespace bayesnet { return entropyValue; } // I(X;Y) = H(Y) - H(Y|X) - double Metrics::mutualInformation(torch::Tensor& firstFeature, torch::Tensor& secondFeature) + double Metrics::mutualInformation(const torch::Tensor& firstFeature, const torch::Tensor& secondFeature) { return entropy(firstFeature) - conditionalEntropy(firstFeature, secondFeature); } @@ -124,7 +124,7 @@ namespace bayesnet { and the indices of the weights as nodes of this square matrix using Kruskal algorithm */ - vector> Metrics::maximumSpanningTree(vector features, Tensor& weights, int root) + vector> Metrics::maximumSpanningTree(const vector& features, const Tensor& weights, const int root) { auto mst = MST(features, weights, root); return mst.maximumSpanningTree(); diff --git a/src/BayesNet/BayesMetrics.h b/src/BayesNet/BayesMetrics.h index 183cfcc..2a2fff3 100644 --- a/src/BayesNet/BayesMetrics.h +++ b/src/BayesNet/BayesMetrics.h @@ -14,15 +14,15 @@ namespace bayesnet { int classNumStates = 0; public: Metrics() = default; - Metrics(Tensor&, vector&, string&, int); + Metrics(const Tensor&, const vector&, const string&, const int); Metrics(const vector>&, const vector&, const vector&, const string&, const int); - double entropy(Tensor&); - double conditionalEntropy(Tensor&, Tensor&); - double mutualInformation(Tensor&, Tensor&); + double entropy(const Tensor&); + double conditionalEntropy(const Tensor&, const Tensor&); + double mutualInformation(const Tensor&, const Tensor&); vector conditionalEdgeWeights(); // To use in Python Tensor conditionalEdge(); vector> doCombinations(const vector&); - vector> maximumSpanningTree(vector features, Tensor& weights, int root); + vector> maximumSpanningTree(const vector& features, const Tensor& weights, const int root); }; } #endif \ No newline at end of file diff --git a/src/BayesNet/Classifier.cc b/src/BayesNet/Classifier.cc index 4d9a4c7..c84ebe6 100644 --- a/src/BayesNet/Classifier.cc +++ b/src/BayesNet/Classifier.cc @@ -7,59 +7,54 @@ namespace bayesnet { Classifier::Classifier(Network model) : model(model), m(0), n(0), metrics(Metrics()), fitted(false) {} Classifier& Classifier::build(vector& features, string className, map>& states) { - Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); - samples = torch::cat({ X, ytmp }, 0); this->features = features; this->className = className; this->states = states; checkFitParameters(); auto n_classes = states[className].size(); - metrics = Metrics(samples, features, className, n_classes); + metrics = Metrics(dataset, features, className, n_classes); model.initialize(); - train(); - if (Xv.empty()) { - // fit with tensors - model.fit(X, y, features, className); - } else { - // fit with vectors - model.fit(Xv, yv, features, className); - } + buildModel(); + m = dataset.size(1); + n = dataset.size(0); + trainModel(); fitted = true; return *this; } + void Classifier::trainModel() + { + model.fit(dataset, features, className); + } + void Classifier::buildDataset(Tensor& ytmp) + { + ytmp = torch::transpose(ytmp.view({ ytmp.size(0), 1 }), 0, 1); + dataset = torch::cat({ dataset, ytmp }, 0); + } // X is nxm where n is the number of features and m the number of samples Classifier& Classifier::fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) { - this->X = X; - this->y = y; - Xv = vector>(); - yv = vector(y.data_ptr(), y.data_ptr() + y.size(0)); + dataset = X; + buildDataset(y); return build(features, className, states); } - void Classifier::generateTensorXFromVector() - { - X = torch::zeros({ static_cast(Xv.size()), static_cast(Xv[0].size()) }, kInt32); - for (int i = 0; i < Xv.size(); ++i) { - X.index_put_({ i, "..." }, torch::tensor(Xv[i], kInt32)); - } - } // X is nxm where n is the number of features and m the number of samples Classifier& Classifier::fit(vector>& X, vector& y, vector& features, string className, map>& states) { - Xv = X; - generateTensorXFromVector(); - this->y = torch::tensor(y, kInt32); - yv = y; + dataset = torch::zeros({ static_cast(X.size()), static_cast(X[0].size()) }, kInt32); + for (int i = 0; i < X.size(); ++i) { + dataset.index_put_({ i, "..." }, torch::tensor(X[i], kInt32)); + } + auto ytmp = torch::tensor(y, kInt32); + buildDataset(ytmp); + return build(features, className, states); + } + Classifier& Classifier::fit(torch::Tensor& dataset, vector& features, string className, map>& states) + { + this->dataset = dataset; return build(features, className, states); } void Classifier::checkFitParameters() { - auto sizes = X.sizes(); - m = sizes[1]; - n = sizes[0]; - if (m != y.size(0)) { - throw invalid_argument("X and y must have the same number of samples"); - } if (n != features.size()) { throw invalid_argument("X and features must have the same number of features"); } @@ -141,5 +136,4 @@ namespace bayesnet { { model.dump_cpt(); } - } \ No newline at end of file diff --git a/src/BayesNet/Classifier.h b/src/BayesNet/Classifier.h index 03c46c6..d492d81 100644 --- a/src/BayesNet/Classifier.h +++ b/src/BayesNet/Classifier.h @@ -10,28 +10,26 @@ using namespace torch; namespace bayesnet { class Classifier : public BaseClassifier { private: - bool fitted; + void buildDataset(torch::Tensor& y); Classifier& build(vector& features, string className, map>& states); protected: + bool fitted; Network model; int m, n; // m: number of samples, n: number of features - Tensor X; // nxm tensor - vector> Xv; // nxm vector - Tensor y; - vector yv; - Tensor samples; // (n+1)xm tensor + Tensor dataset; // (n+1)xm tensor Metrics metrics; vector features; string className; map> states; void checkFitParameters(); - void generateTensorXFromVector(); - virtual void train() = 0; + virtual void buildModel() = 0; + void trainModel(); public: Classifier(Network model); virtual ~Classifier() = default; Classifier& fit(vector>& X, vector& y, vector& features, string className, map>& states) override; Classifier& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; + Classifier& fit(torch::Tensor& dataset, vector& features, string className, map>& states) override; void addNodes(); int getNumberOfNodes() override; int getNumberOfEdges() override; diff --git a/src/BayesNet/Ensemble.cc b/src/BayesNet/Ensemble.cc index 8cbd17c..d38430d 100644 --- a/src/BayesNet/Ensemble.cc +++ b/src/BayesNet/Ensemble.cc @@ -3,54 +3,15 @@ namespace bayesnet { using namespace torch; - Ensemble::Ensemble() : n_models(0), metrics(Metrics()), fitted(false) {} - Ensemble& Ensemble::build(vector& features, string className, map>& states) + Ensemble::Ensemble() : Classifier(Network()) {} + + void Ensemble::trainModel() { - Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); - samples = torch::cat({ X, ytmp }, 0); - this->features = features; - this->className = className; - this->states = states; - auto n_classes = states[className].size(); - metrics = Metrics(samples, features, className, n_classes); - // Build models - train(); - // Train models n_models = models.size(); for (auto i = 0; i < n_models; ++i) { - if (Xv.empty()) { - // fit with tensors - models[i]->fit(X, y, features, className, states); - } else { - // fit with vectors - models[i]->fit(Xv, yv, features, className, states); - } + // fit with vectors + models[i]->fit(dataset, features, className, states); } - fitted = true; - return *this; - } - void Ensemble::generateTensorXFromVector() - { - X = torch::zeros({ static_cast(Xv.size()), static_cast(Xv[0].size()) }, kInt32); - for (int i = 0; i < Xv.size(); ++i) { - X.index_put_({ i, "..." }, torch::tensor(Xv[i], kInt32)); - } - } - Ensemble& Ensemble::fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) - { - this->X = X; - this->y = y; - Xv = vector>(); - yv = vector(y.data_ptr(), y.data_ptr() + y.size(0)); - return build(features, className, states); - } - Ensemble& Ensemble::fit(vector>& X, vector& y, vector& features, string className, map>& states) - { - Xv = X; - generateTensorXFromVector(); - this->y = torch::tensor(y, kInt32); - yv = y; - return build(features, className, states); } vector Ensemble::voting(Tensor& y_pred) { @@ -132,7 +93,6 @@ namespace bayesnet { } } return (double)correct / y_pred.size(); - } vector Ensemble::show() { diff --git a/src/BayesNet/Ensemble.h b/src/BayesNet/Ensemble.h index 322032e..8efa0b7 100644 --- a/src/BayesNet/Ensemble.h +++ b/src/BayesNet/Ensemble.h @@ -8,30 +8,17 @@ using namespace std; using namespace torch; namespace bayesnet { - class Ensemble : public BaseClassifier { + class Ensemble : public Classifier { private: Ensemble& build(vector& features, string className, map>& states); protected: unsigned n_models; - bool fitted; vector> models; - Tensor X; - vector> Xv; - Tensor y; - vector yv; - Tensor samples; - Metrics metrics; - vector features; - string className; - map> states; - void virtual train() = 0; + void trainModel(); vector voting(Tensor& y_pred); - void generateTensorXFromVector(); public: Ensemble(); virtual ~Ensemble() = default; - Ensemble& fit(vector>& X, vector& y, vector& features, string className, map>& states) override; - Ensemble& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; Tensor predict(Tensor& X) override; vector predict(vector>& X) override; float score(Tensor& X, Tensor& y) override; diff --git a/src/BayesNet/KDB.cc b/src/BayesNet/KDB.cc index a0ab434..6988671 100644 --- a/src/BayesNet/KDB.cc +++ b/src/BayesNet/KDB.cc @@ -4,7 +4,7 @@ namespace bayesnet { using namespace torch; KDB::KDB(int k, float theta) : Classifier(Network()), k(k), theta(theta) {} - void KDB::train() + void KDB::buildModel() { /* 1. For each feature Xi, compute mutual information, I(X;C), @@ -28,9 +28,10 @@ namespace bayesnet { // 1. For each feature Xi, compute mutual information, I(X;C), // where C is the class. addNodes(); + const Tensor& y = dataset.index({ -1, "..." }); vector mi; for (auto i = 0; i < features.size(); i++) { - Tensor firstFeature = X.index({ i, "..." }); + Tensor firstFeature = dataset.index({ i, "..." }); mi.push_back(metrics.mutualInformation(firstFeature, y)); } // 2. Compute class conditional mutual information I(Xi;XjIC), f or each diff --git a/src/BayesNet/KDB.h b/src/BayesNet/KDB.h index 11a69d7..028bee8 100644 --- a/src/BayesNet/KDB.h +++ b/src/BayesNet/KDB.h @@ -11,7 +11,7 @@ namespace bayesnet { float theta; void add_m_edges(int idx, vector& S, Tensor& weights); protected: - void train() override; + void buildModel() override; public: explicit KDB(int k, float theta = 0.03); virtual ~KDB() {}; diff --git a/src/BayesNet/KDBLd.cc b/src/BayesNet/KDBLd.cc index d2cbed4..63344af 100644 --- a/src/BayesNet/KDBLd.cc +++ b/src/BayesNet/KDBLd.cc @@ -2,7 +2,7 @@ namespace bayesnet { using namespace std; - KDBLd::KDBLd(int k) : KDB(k), Proposal(KDB::Xv, KDB::yv, features, className) {} + KDBLd::KDBLd(int k) : KDB(k), Proposal(dataset, features, className) {} KDBLd& KDBLd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { // This first part should go in a Classifier method called fit_local_discretization o fit_float... @@ -12,15 +12,10 @@ namespace bayesnet { y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y fit_local_discretization(states, y); - generateTensorXFromVector(); // We have discretized the input data // 1st we need to fit the model to build the normal KDB structure, KDB::fit initializes the base Bayesian network - KDB::fit(KDB::Xv, KDB::yv, features, className, states); + KDB::fit(dataset, features, className, states); localDiscretizationProposal(states, model); - generateTensorXFromVector(); - Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); - samples = torch::cat({ X, ytmp }, 0); - model.fit(KDB::Xv, KDB::yv, features, className); return *this; } Tensor KDBLd::predict(Tensor& X) diff --git a/src/BayesNet/Mst.cc b/src/BayesNet/Mst.cc index 3a48d05..b915d76 100644 --- a/src/BayesNet/Mst.cc +++ b/src/BayesNet/Mst.cc @@ -94,7 +94,7 @@ namespace bayesnet { return result; } - MST::MST(vector& features, Tensor& weights, int root) : features(features), weights(weights), root(root) {} + MST::MST(const vector& features, const Tensor& weights, const int root) : features(features), weights(weights), root(root) {} vector> MST::maximumSpanningTree() { auto num_features = features.size(); diff --git a/src/BayesNet/Mst.h b/src/BayesNet/Mst.h index 71a46a5..e0f3372 100644 --- a/src/BayesNet/Mst.h +++ b/src/BayesNet/Mst.h @@ -13,7 +13,7 @@ namespace bayesnet { int root = 0; public: MST() = default; - MST(vector& features, Tensor& weights, int root); + MST(const vector& features, const Tensor& weights, const int root); vector> maximumSpanningTree(); }; class Graph { diff --git a/src/BayesNet/Network.cc b/src/BayesNet/Network.cc index 2a37de4..5b6307a 100644 --- a/src/BayesNet/Network.cc +++ b/src/BayesNet/Network.cc @@ -20,7 +20,6 @@ namespace bayesnet { classNumStates = 0; fitted = false; nodes.clear(); - dataset.clear(); samples = torch::Tensor(); } float Network::getmaxThreads() @@ -134,18 +133,22 @@ namespace bayesnet { classNumStates = nodes[className]->getNumStates(); } // X comes in nxm, where n is the number of features and m the number of samples - void Network::fit(torch::Tensor& X, torch::Tensor& y, const vector& featureNames, const string& className) + void Network::fit(const torch::Tensor& X, const torch::Tensor& y, const vector& featureNames, const string& className) { checkFitData(X.size(1), X.size(0), y.size(0), featureNames, className); this->className = className; - dataset.clear(); Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); samples = torch::cat({ X , ytmp }, 0); for (int i = 0; i < featureNames.size(); ++i) { auto row_feature = X.index({ i, "..." }); - dataset[featureNames[i]] = vector(row_feature.data_ptr(), row_feature.data_ptr() + row_feature.size(0));; } - dataset[className] = vector(y.data_ptr(), y.data_ptr() + y.size(0)); + completeFit(); + } + void Network::fit(const torch::Tensor& samples, const vector& featureNames, const string& className) + { + checkFitData(samples.size(1), samples.size(0) - 1, samples.size(1), featureNames, className); + this->className = className; + this->samples = samples; completeFit(); } // input_data comes in nxm, where n is the number of features and m the number of samples @@ -153,14 +156,11 @@ namespace bayesnet { { checkFitData(input_data[0].size(), input_data.size(), labels.size(), featureNames, className); this->className = className; - dataset.clear(); - // Build dataset & tensor of samples (nxm) (n+1 because of the class) + // Build tensor of samples (nxm) (n+1 because of the class) samples = torch::zeros({ static_cast(input_data.size() + 1), static_cast(input_data[0].size()) }, torch::kInt32); for (int i = 0; i < featureNames.size(); ++i) { - dataset[featureNames[i]] = input_data[i]; samples.index_put_({ i, "..." }, torch::tensor(input_data[i], torch::kInt32)); } - dataset[className] = labels; samples.index_put_({ -1, "..." }, torch::tensor(labels, torch::kInt32)); completeFit(); } @@ -188,7 +188,7 @@ namespace bayesnet { auto& pair = *std::next(nodes.begin(), nextNodeIndex); ++nextNodeIndex; lock.unlock(); - pair.second->computeCPT(dataset, laplaceSmoothing); + pair.second->computeCPT(samples, features, laplaceSmoothing); lock.lock(); nodes[pair.first] = std::move(pair.second); lock.unlock(); @@ -328,12 +328,12 @@ namespace bayesnet { mutex mtx; for (int i = 0; i < classNumStates; ++i) { threads.emplace_back([this, &result, &evidence, i, &mtx]() { - auto completeEvidence = map(evidence); - completeEvidence[getClassName()] = i; + auto completeEvidence = map(evidence); + completeEvidence[getClassName()] = i; double factor = computeFactor(completeEvidence); lock_guard lock(mtx); result[i] = factor; - }); + }); } for (auto& thread : threads) { thread.join(); diff --git a/src/BayesNet/Network.h b/src/BayesNet/Network.h index b27125c..616235a 100644 --- a/src/BayesNet/Network.h +++ b/src/BayesNet/Network.h @@ -8,11 +8,10 @@ namespace bayesnet { class Network { private: map> nodes; - map> dataset; bool fitted; float maxThreads = 0.95; int classNumStates; - vector features; // Including class + vector features; // Including classname string className; int laplaceSmoothing = 1; torch::Tensor samples; // nxm tensor used to fit the model @@ -44,7 +43,8 @@ namespace bayesnet { int getClassNumStates(); string getClassName(); void fit(const vector>&, const vector&, const vector&, const string&); - void fit(torch::Tensor&, torch::Tensor&, const vector&, const string&); + void fit(const torch::Tensor&, const torch::Tensor&, const vector&, const string&); + void fit(const torch::Tensor&, const vector&, const string&); vector predict(const vector>&); // Return mx1 vector of predictions torch::Tensor predict(const torch::Tensor&); // Return mx1 tensor of predictions //Computes the conditional edge weight of variable index u and v conditioned on class_node diff --git a/src/BayesNet/Node.cc b/src/BayesNet/Node.cc index 3fca064..6669819 100644 --- a/src/BayesNet/Node.cc +++ b/src/BayesNet/Node.cc @@ -84,7 +84,7 @@ namespace bayesnet { } return result; } - void Node::computeCPT(map>& dataset, const int laplaceSmoothing) + void Node::computeCPT(const torch::Tensor& dataset, const vector& features, const int laplaceSmoothing) { dimensions.clear(); // Get dimensions of the CPT @@ -94,10 +94,22 @@ namespace bayesnet { // Create a tensor of zeros with the dimensions of the CPT cpTable = torch::zeros(dimensions, torch::kFloat) + laplaceSmoothing; // Fill table with counts - for (int n_sample = 0; n_sample < dataset[name].size(); ++n_sample) { + auto pos = find(features.begin(), features.end(), name); + if (pos == features.end()) { + throw logic_error("Feature " + name + " not found in dataset"); + } + int name_index = pos - features.begin(); + for (int n_sample = 0; n_sample < dataset.size(1); ++n_sample) { torch::List> coordinates; - coordinates.push_back(torch::tensor(dataset[name][n_sample])); - transform(parents.begin(), parents.end(), back_inserter(coordinates), [&dataset, &n_sample](const auto& parent) { return torch::tensor(dataset[parent->getName()][n_sample]); }); + coordinates.push_back(dataset.index({ name_index, n_sample })); + for (auto parent : parents) { + pos = find(features.begin(), features.end(), parent->getName()); + if (pos == features.end()) { + throw logic_error("Feature parent " + parent->getName() + " not found in dataset"); + } + int parent_index = pos - features.begin(); + coordinates.push_back(dataset.index({ parent_index, n_sample })); + } // Increment the count of the corresponding coordinate cpTable.index_put_({ coordinates }, cpTable.index({ coordinates }) + 1); } diff --git a/src/BayesNet/Node.h b/src/BayesNet/Node.h index b923dec..f4eb320 100644 --- a/src/BayesNet/Node.h +++ b/src/BayesNet/Node.h @@ -26,7 +26,7 @@ namespace bayesnet { vector& getParents(); vector& getChildren(); torch::Tensor& getCPT(); - void computeCPT(map>&, const int); + void computeCPT(const torch::Tensor&, const vector&, const int); int getNumStates() const; void setNumStates(int); unsigned minFill(); diff --git a/src/BayesNet/Proposal.cc b/src/BayesNet/Proposal.cc index c1d3626..19992c6 100644 --- a/src/BayesNet/Proposal.cc +++ b/src/BayesNet/Proposal.cc @@ -2,7 +2,7 @@ #include "ArffFiles.h" namespace bayesnet { - Proposal::Proposal(vector>& Xv_, vector& yv_, vector& features_, string& className_) : Xv(Xv_), yv(yv_), pFeatures(features_), pClassName(className_) {} + Proposal::Proposal(torch::Tensor& dataset_, vector& features_, string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_), m(dataset_.size(1)), n(dataset_.size(0) - 1) {} Proposal::~Proposal() { for (auto& [key, value] : discretizers) { @@ -16,7 +16,6 @@ namespace bayesnet { auto order = model.topological_sort(); auto& nodes = model.getNodes(); vector indicesToReDiscretize; - auto n_samples = Xf.size(1); bool upgrade = false; // Flag to check if we need to upgrade the model for (auto feature : order) { auto nodeParents = nodes[feature]->getParents(); @@ -30,13 +29,13 @@ namespace bayesnet { parents.erase(remove(parents.begin(), parents.end(), pClassName), parents.end()); // Get the indices of the parents vector indices; + indices.push_back(-1); // Add class index transform(parents.begin(), parents.end(), back_inserter(indices), [&](const auto& p) {return find(pFeatures.begin(), pFeatures.end(), p) - pFeatures.begin(); }); // Now we fit the discretizer of the feature, conditioned on its parents and the class i.e. discretizer.fit(X[index], X[indices] + y) - vector yJoinParents; - transform(yv.begin(), yv.end(), back_inserter(yJoinParents), [&](const auto& p) {return to_string(p); }); + vector yJoinParents(indices.size()); for (auto idx : indices) { - for (int i = 0; i < n_samples; ++i) { - yJoinParents[i] += to_string(Xv[idx][i]); + for (int i = 0; i < n; ++i) { + yJoinParents[i] += to_string(pDataset.index({ idx, i }).item()); } } auto arff = ArffFiles(); @@ -59,7 +58,7 @@ namespace bayesnet { for (auto index : indicesToReDiscretize) { auto Xt_ptr = Xf.index({ index }).data_ptr(); auto Xt = vector(Xt_ptr, Xt_ptr + Xf.size(1)); - Xv[index] = discretizers[pFeatures[index]]->transform(Xt); + pDataset.index_put_({ index, "..." }, torch::tensor(discretizers[pFeatures[index]]->transform(Xt))); auto xStates = vector(discretizers[pFeatures[index]]->getCutPoints().size() + 1); iota(xStates.begin(), xStates.end(), 0); //Update new states of the feature/node @@ -69,16 +68,15 @@ namespace bayesnet { } void Proposal::fit_local_discretization(map>& states, torch::Tensor& y) { - // Sharing Xv and yv with Classifier - Xv = vector>(); - yv = vector(y.data_ptr(), y.data_ptr() + y.size(0)); + pDataset = torch::zeros({ n + 1, m }, kInt32); + auto yv = vector(y.data_ptr(), y.data_ptr() + y.size(0)); // discretize input data by feature(row) - for (int i = 0; i < pFeatures.size(); ++i) { + for (auto i = 0; i < pFeatures.size(); ++i) { auto* discretizer = new mdlp::CPPFImdlp(); auto Xt_ptr = Xf.index({ i }).data_ptr(); auto Xt = vector(Xt_ptr, Xt_ptr + Xf.size(1)); discretizer->fit(Xt, yv); - Xv.push_back(discretizer->transform(Xt)); + pDataset.index_put_({ i, "..." }, torch::tensor(discretizer->transform(Xt))); auto xStates = vector(discretizer->getCutPoints().size() + 1); iota(xStates.begin(), xStates.end(), 0); states[pFeatures[i]] = xStates; diff --git a/src/BayesNet/Proposal.h b/src/BayesNet/Proposal.h index a5650b4..606ed5a 100644 --- a/src/BayesNet/Proposal.h +++ b/src/BayesNet/Proposal.h @@ -10,20 +10,21 @@ namespace bayesnet { class Proposal { public: - Proposal(vector>& Xv_, vector& yv_, vector& features_, string& className_); + Proposal(torch::Tensor& pDataset, vector& features_, string& className_); virtual ~Proposal(); protected: torch::Tensor prepareX(torch::Tensor& X); void localDiscretizationProposal(map>& states, Network& model); void fit_local_discretization(map>& states, torch::Tensor& y); torch::Tensor Xf; // X continuous nxm tensor + torch::Tensor y; // y discrete nx1 tensor map discretizers; + int m, n; private: + torch::Tensor& pDataset; // (n+1)xm tensor vector& pFeatures; string& pClassName; - vector>& Xv; // X discrete nxm vector - vector& yv; }; } -#endif \ No newline at end of file +#endif \ No newline at end of file diff --git a/src/BayesNet/SPODE.cc b/src/BayesNet/SPODE.cc index a627cca..eba6542 100644 --- a/src/BayesNet/SPODE.cc +++ b/src/BayesNet/SPODE.cc @@ -4,7 +4,7 @@ namespace bayesnet { SPODE::SPODE(int root) : Classifier(Network()), root(root) {} - void SPODE::train() + void SPODE::buildModel() { // 0. Add all nodes to the model addNodes(); diff --git a/src/BayesNet/SPODE.h b/src/BayesNet/SPODE.h index 4625714..d441e66 100644 --- a/src/BayesNet/SPODE.h +++ b/src/BayesNet/SPODE.h @@ -7,7 +7,7 @@ namespace bayesnet { private: int root; protected: - void train() override; + void buildModel() override; public: explicit SPODE(int root); virtual ~SPODE() {}; diff --git a/src/BayesNet/SPODELd.cc b/src/BayesNet/SPODELd.cc index f7df9b6..8b9fe2f 100644 --- a/src/BayesNet/SPODELd.cc +++ b/src/BayesNet/SPODELd.cc @@ -2,7 +2,7 @@ namespace bayesnet { using namespace std; - SPODELd::SPODELd(int root) : SPODE(root), Proposal(SPODE::Xv, SPODE::yv, features, className) {} + SPODELd::SPODELd(int root) : SPODE(root), Proposal(dataset, features, className) {} SPODELd& SPODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { // This first part should go in a Classifier method called fit_local_discretization o fit_float... @@ -12,15 +12,11 @@ namespace bayesnet { y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y fit_local_discretization(states, y); - generateTensorXFromVector(); // We have discretized the input data // 1st we need to fit the model to build the normal SPODE structure, SPODE::fit initializes the base Bayesian network - SPODE::fit(SPODE::Xv, SPODE::yv, features, className, states); + SPODE::fit(dataset, features, className, states); localDiscretizationProposal(states, model); - generateTensorXFromVector(); - Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); - samples = torch::cat({ X, ytmp }, 0); - model.fit(SPODE::Xv, SPODE::yv, features, className); + //model.fit(SPODE::Xv, SPODE::yv, features, className); return *this; } Tensor SPODELd::predict(Tensor& X) diff --git a/src/BayesNet/TAN.cc b/src/BayesNet/TAN.cc index f47d7c5..c77275c 100644 --- a/src/BayesNet/TAN.cc +++ b/src/BayesNet/TAN.cc @@ -5,16 +5,16 @@ namespace bayesnet { TAN::TAN() : Classifier(Network()) {} - void TAN::train() + void TAN::buildModel() { // 0. Add all nodes to the model addNodes(); // 1. Compute mutual information between each feature and the class and set the root node // as the highest mutual information with the class auto mi = vector >(); - Tensor class_dataset = samples.index({ -1, "..." }); + Tensor class_dataset = dataset.index({ -1, "..." }); for (int i = 0; i < static_cast(features.size()); ++i) { - Tensor feature_dataset = samples.index({ i, "..." }); + Tensor feature_dataset = dataset.index({ i, "..." }); auto mi_value = metrics.mutualInformation(class_dataset, feature_dataset); mi.push_back({ i, mi_value }); } diff --git a/src/BayesNet/TAN.h b/src/BayesNet/TAN.h index 5c7cf49..6d95e21 100644 --- a/src/BayesNet/TAN.h +++ b/src/BayesNet/TAN.h @@ -7,7 +7,7 @@ namespace bayesnet { class TAN : public Classifier { private: protected: - void train() override; + void buildModel() override; public: TAN(); virtual ~TAN() {}; diff --git a/src/BayesNet/TANLd.cc b/src/BayesNet/TANLd.cc index f0fe110..49ffa96 100644 --- a/src/BayesNet/TANLd.cc +++ b/src/BayesNet/TANLd.cc @@ -2,7 +2,7 @@ namespace bayesnet { using namespace std; - TANLd::TANLd() : TAN(), Proposal(TAN::Xv, TAN::yv, features, className) {} + TANLd::TANLd() : TAN(), Proposal(dataset, features, className) {} TANLd& TANLd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { // This first part should go in a Classifier method called fit_local_discretization o fit_float... @@ -12,15 +12,11 @@ namespace bayesnet { y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y fit_local_discretization(states, y); - generateTensorXFromVector(); // We have discretized the input data // 1st we need to fit the model to build the normal TAN structure, TAN::fit initializes the base Bayesian network - TAN::fit(TAN::Xv, TAN::yv, features, className, states); + TAN::fit(dataset, features, className, states); localDiscretizationProposal(states, model); - generateTensorXFromVector(); - Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); - samples = torch::cat({ X, ytmp }, 0); - model.fit(TAN::Xv, TAN::yv, features, className); + //model.fit(dataset, features, className); return *this; } Tensor TANLd::predict(Tensor& X) -- 2.45.2 From ef1bffcac314bdccebf888dff1067125cd68ee47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Monta=C3=B1ana?= Date: Mon, 7 Aug 2023 13:50:11 +0200 Subject: [PATCH 2/6] Fixed normal classifiers --- .vscode/launch.json | 3 ++- src/BayesNet/AODELd.h | 2 +- src/BayesNet/Classifier.cc | 25 +++++++++++++++++-------- src/BayesNet/Classifier.h | 2 +- src/BayesNet/Ensemble.h | 2 +- 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 7241ae2..8eeff68 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -25,7 +25,8 @@ "program": "${workspaceFolder}/build/src/Platform/main", "args": [ "-m", - "AODELd", + "AODE", + "--discretize", "-p", "/Users/rmontanana/Code/discretizbench/datasets", "--stratified", diff --git a/src/BayesNet/AODELd.h b/src/BayesNet/AODELd.h index c8db41d..74b74b1 100644 --- a/src/BayesNet/AODELd.h +++ b/src/BayesNet/AODELd.h @@ -8,7 +8,7 @@ namespace bayesnet { using namespace std; class AODELd : public Ensemble, public Proposal { private: - void trainModel(); + void trainModel() override; void buildModel() override; public: AODELd(); diff --git a/src/BayesNet/Classifier.cc b/src/BayesNet/Classifier.cc index c84ebe6..c0f1895 100644 --- a/src/BayesNet/Classifier.cc +++ b/src/BayesNet/Classifier.cc @@ -10,26 +10,35 @@ namespace bayesnet { this->features = features; this->className = className; this->states = states; + m = dataset.size(1); + n = dataset.size(0) - 1; checkFitParameters(); auto n_classes = states[className].size(); metrics = Metrics(dataset, features, className, n_classes); model.initialize(); buildModel(); - m = dataset.size(1); - n = dataset.size(0); trainModel(); fitted = true; return *this; } + + void Classifier::buildDataset(Tensor& ytmp) + { + try { + auto yresized = torch::transpose(ytmp.view({ ytmp.size(0), 1 }), 0, 1); + dataset = torch::cat({ dataset, yresized }, 0); + } + catch (const std::exception& e) { + std::cerr << e.what() << '\n'; + cout << "X dimensions: " << dataset.sizes() << "\n"; + cout << "y dimensions: " << ytmp.sizes() << "\n"; + exit(1); + } + } void Classifier::trainModel() { model.fit(dataset, features, className); } - void Classifier::buildDataset(Tensor& ytmp) - { - ytmp = torch::transpose(ytmp.view({ ytmp.size(0), 1 }), 0, 1); - dataset = torch::cat({ dataset, ytmp }, 0); - } // X is nxm where n is the number of features and m the number of samples Classifier& Classifier::fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) { @@ -56,7 +65,7 @@ namespace bayesnet { void Classifier::checkFitParameters() { if (n != features.size()) { - throw invalid_argument("X and features must have the same number of features"); + throw invalid_argument("X " + to_string(n) + " and features " + to_string(features.size()) + " must have the same number of features"); } if (states.find(className) == states.end()) { throw invalid_argument("className not found in states"); diff --git a/src/BayesNet/Classifier.h b/src/BayesNet/Classifier.h index d492d81..7e88bd3 100644 --- a/src/BayesNet/Classifier.h +++ b/src/BayesNet/Classifier.h @@ -23,7 +23,7 @@ namespace bayesnet { map> states; void checkFitParameters(); virtual void buildModel() = 0; - void trainModel(); + virtual void trainModel(); public: Classifier(Network model); virtual ~Classifier() = default; diff --git a/src/BayesNet/Ensemble.h b/src/BayesNet/Ensemble.h index 8efa0b7..f36d1ad 100644 --- a/src/BayesNet/Ensemble.h +++ b/src/BayesNet/Ensemble.h @@ -14,7 +14,7 @@ namespace bayesnet { protected: unsigned n_models; vector> models; - void trainModel(); + void trainModel() override; vector voting(Tensor& y_pred); public: Ensemble(); -- 2.45.2 From 323444b74ad9fd372ed5e96cb1352808f612e526 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Monta=C3=B1ana?= Date: Tue, 8 Aug 2023 01:53:41 +0200 Subject: [PATCH 3/6] const functions --- .vscode/launch.json | 3 +-- src/BayesNet/AODE.cc | 2 +- src/BayesNet/AODE.h | 2 +- src/BayesNet/AODELd.cc | 31 ++++++++++++++++++++----------- src/BayesNet/AODELd.h | 7 +++---- src/BayesNet/BaseClassifier.h | 14 ++++++++------ src/BayesNet/CMakeLists.txt | 4 +++- src/BayesNet/Classifier.cc | 12 ++++++------ src/BayesNet/Classifier.h | 14 +++++++------- src/BayesNet/Ensemble.cc | 10 +++++----- src/BayesNet/Ensemble.h | 14 +++++++------- src/BayesNet/KDB.cc | 2 +- src/BayesNet/KDB.h | 2 +- src/BayesNet/KDBLd.cc | 2 +- src/BayesNet/KDBLd.h | 2 +- src/BayesNet/Network.cc | 20 ++++++++++++-------- src/BayesNet/Network.h | 17 +++++++++-------- src/BayesNet/Proposal.cc | 9 ++++++--- src/BayesNet/Proposal.h | 1 - src/BayesNet/SPODE.cc | 2 +- src/BayesNet/SPODE.h | 2 +- src/BayesNet/SPODELd.cc | 10 +++++++--- src/BayesNet/SPODELd.h | 4 ++-- src/BayesNet/TAN.cc | 2 +- src/BayesNet/TAN.h | 2 +- src/BayesNet/TANLd.cc | 4 ++-- src/BayesNet/TANLd.h | 2 +- 27 files changed, 109 insertions(+), 87 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 8eeff68..7241ae2 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -25,8 +25,7 @@ "program": "${workspaceFolder}/build/src/Platform/main", "args": [ "-m", - "AODE", - "--discretize", + "AODELd", "-p", "/Users/rmontanana/Code/discretizbench/datasets", "--stratified", diff --git a/src/BayesNet/AODE.cc b/src/BayesNet/AODE.cc index 66c71da..7e6a95f 100644 --- a/src/BayesNet/AODE.cc +++ b/src/BayesNet/AODE.cc @@ -9,7 +9,7 @@ namespace bayesnet { models.push_back(std::make_unique(i)); } } - vector AODE::graph(const string& title) + vector AODE::graph(const string& title) const { return Ensemble::graph(title); } diff --git a/src/BayesNet/AODE.h b/src/BayesNet/AODE.h index 5447fc0..3d58851 100644 --- a/src/BayesNet/AODE.h +++ b/src/BayesNet/AODE.h @@ -9,7 +9,7 @@ namespace bayesnet { public: AODE(); virtual ~AODE() {}; - vector graph(const string& title = "AODE") override; + vector graph(const string& title = "AODE") const override; }; } #endif \ No newline at end of file diff --git a/src/BayesNet/AODELd.cc b/src/BayesNet/AODELd.cc index 18e3761..8a656cc 100644 --- a/src/BayesNet/AODELd.cc +++ b/src/BayesNet/AODELd.cc @@ -1,37 +1,46 @@ #include "AODELd.h" +#include "Models.h" namespace bayesnet { using namespace std; AODELd::AODELd() : Ensemble(), Proposal(dataset, features, className) {} AODELd& AODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { + // This first part should go in a Classifier method called fit_local_discretization o fit_float... features = features_; className = className_; - states = states_; - buildModel(); - trainModel(); - n_models = models.size(); - fitted = true; + Xf = X_; + y = y_; + // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y + fit_local_discretization(states, y); + // We have discretized the input data + // 1st we need to fit the model to build the normal TAN structure, TAN::fit initializes the base Bayesian network + Ensemble::fit(dataset, features, className, states); return *this; + } void AODELd::buildModel() { models.clear(); + cout << "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!" << endl; for (int i = 0; i < features.size(); ++i) { - models.push_back(std::make_unique(i)); + models.push_back(Models::instance().create("SPODELd")); + models[i]->test(); } + n_models = models.size(); } void AODELd::trainModel() { + cout << "dataset: " << dataset.sizes() << endl; + cout << "features: " << features.size() << endl; + cout << "className: " << className << endl; + cout << "states: " << states.size() << endl; for (const auto& model : models) { model->fit(dataset, features, className, states); + model->test(); } } - Tensor AODELd::predict(Tensor& X) - { - return Ensemble::predict(X); - } - vector AODELd::graph(const string& name) + vector AODELd::graph(const string& name) const { return Ensemble::graph(name); } diff --git a/src/BayesNet/AODELd.h b/src/BayesNet/AODELd.h index 74b74b1..14be0c4 100644 --- a/src/BayesNet/AODELd.h +++ b/src/BayesNet/AODELd.h @@ -7,15 +7,14 @@ namespace bayesnet { using namespace std; class AODELd : public Ensemble, public Proposal { - private: + protected: void trainModel() override; void buildModel() override; public: AODELd(); + AODELd& fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) override; virtual ~AODELd() = default; - AODELd& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; - vector graph(const string& name = "AODE") override; - Tensor predict(Tensor& X) override; + vector graph(const string& name = "AODE") const override; static inline string version() { return "0.0.1"; }; }; } diff --git a/src/BayesNet/BaseClassifier.h b/src/BayesNet/BaseClassifier.h index e95fafc..ff202e1 100644 --- a/src/BayesNet/BaseClassifier.h +++ b/src/BayesNet/BaseClassifier.h @@ -5,6 +5,8 @@ namespace bayesnet { using namespace std; class BaseClassifier { + protected: + virtual void trainModel() = 0; public: // X is nxm vector, y is nx1 vector virtual BaseClassifier& fit(vector>& X, vector& y, vector& features, string className, map>& states) = 0; @@ -16,14 +18,14 @@ namespace bayesnet { vector virtual predict(vector>& X) = 0; float virtual score(vector>& X, vector& y) = 0; float virtual score(torch::Tensor& X, torch::Tensor& y) = 0; - int virtual getNumberOfNodes() = 0; - int virtual getNumberOfEdges() = 0; - int virtual getNumberOfStates() = 0; - vector virtual show() = 0; - vector virtual graph(const string& title = "") = 0; + int virtual getNumberOfNodes()const = 0; + int virtual getNumberOfEdges()const = 0; + int virtual getNumberOfStates() const = 0; + vector virtual show() const = 0; + vector virtual graph(const string& title = "") const = 0; const string inline getVersion() const { return "0.1.0"; }; vector virtual topological_order() = 0; - void virtual dump_cpt() = 0; + void virtual dump_cpt()const = 0; }; } #endif \ No newline at end of file diff --git a/src/BayesNet/CMakeLists.txt b/src/BayesNet/CMakeLists.txt index 5df47d5..a2b9126 100644 --- a/src/BayesNet/CMakeLists.txt +++ b/src/BayesNet/CMakeLists.txt @@ -1,5 +1,7 @@ include_directories(${BayesNet_SOURCE_DIR}/lib/mdlp) include_directories(${BayesNet_SOURCE_DIR}/lib/Files) +include_directories(${BayesNet_SOURCE_DIR}/src/BayesNet) +include_directories(${BayesNet_SOURCE_DIR}/src/Platform) add_library(BayesNet bayesnetUtils.cc Network.cc Node.cc BayesMetrics.cc Classifier.cc - KDB.cc TAN.cc SPODE.cc Ensemble.cc AODE.cc TANLd.cc KDBLd.cc SPODELd.cc AODELd.cc Mst.cc Proposal.cc) + KDB.cc TAN.cc SPODE.cc Ensemble.cc AODE.cc TANLd.cc KDBLd.cc SPODELd.cc AODELd.cc Mst.cc Proposal.cc ${BayesNet_SOURCE_DIR}/src/Platform/Models.cc) target_link_libraries(BayesNet mdlp ArffFiles "${TORCH_LIBRARIES}") \ No newline at end of file diff --git a/src/BayesNet/Classifier.cc b/src/BayesNet/Classifier.cc index c0f1895..7f41839 100644 --- a/src/BayesNet/Classifier.cc +++ b/src/BayesNet/Classifier.cc @@ -112,7 +112,7 @@ namespace bayesnet { } return model.score(X, y); } - vector Classifier::show() + vector Classifier::show() const { return model.show(); } @@ -124,16 +124,16 @@ namespace bayesnet { } model.addNode(className); } - int Classifier::getNumberOfNodes() + int Classifier::getNumberOfNodes() const { // Features does not include class return fitted ? model.getFeatures().size() + 1 : 0; } - int Classifier::getNumberOfEdges() + int Classifier::getNumberOfEdges() const { - return fitted ? model.getEdges().size() : 0; + return fitted ? model.getNumEdges() : 0; } - int Classifier::getNumberOfStates() + int Classifier::getNumberOfStates() const { return fitted ? model.getStates() : 0; } @@ -141,7 +141,7 @@ namespace bayesnet { { return model.topological_sort(); } - void Classifier::dump_cpt() + void Classifier::dump_cpt() const { model.dump_cpt(); } diff --git a/src/BayesNet/Classifier.h b/src/BayesNet/Classifier.h index 7e88bd3..2e736a3 100644 --- a/src/BayesNet/Classifier.h +++ b/src/BayesNet/Classifier.h @@ -23,7 +23,7 @@ namespace bayesnet { map> states; void checkFitParameters(); virtual void buildModel() = 0; - virtual void trainModel(); + void trainModel() override; public: Classifier(Network model); virtual ~Classifier() = default; @@ -31,16 +31,16 @@ namespace bayesnet { Classifier& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; Classifier& fit(torch::Tensor& dataset, vector& features, string className, map>& states) override; void addNodes(); - int getNumberOfNodes() override; - int getNumberOfEdges() override; - int getNumberOfStates() override; + int getNumberOfNodes() const override; + int getNumberOfEdges() const override; + int getNumberOfStates() const override; Tensor predict(Tensor& X) override; vector predict(vector>& X) override; float score(Tensor& X, Tensor& y) override; float score(vector>& X, vector& y) override; - vector show() override; - vector topological_order() override; - void dump_cpt() override; + vector show() const override; + vector topological_order() override; + void dump_cpt() const override; }; } #endif diff --git a/src/BayesNet/Ensemble.cc b/src/BayesNet/Ensemble.cc index d38430d..34c6894 100644 --- a/src/BayesNet/Ensemble.cc +++ b/src/BayesNet/Ensemble.cc @@ -94,7 +94,7 @@ namespace bayesnet { } return (double)correct / y_pred.size(); } - vector Ensemble::show() + vector Ensemble::show() const { auto result = vector(); for (auto i = 0; i < n_models; ++i) { @@ -103,7 +103,7 @@ namespace bayesnet { } return result; } - vector Ensemble::graph(const string& title) + vector Ensemble::graph(const string& title) const { auto result = vector(); for (auto i = 0; i < n_models; ++i) { @@ -112,7 +112,7 @@ namespace bayesnet { } return result; } - int Ensemble::getNumberOfNodes() + int Ensemble::getNumberOfNodes() const { int nodes = 0; for (auto i = 0; i < n_models; ++i) { @@ -120,7 +120,7 @@ namespace bayesnet { } return nodes; } - int Ensemble::getNumberOfEdges() + int Ensemble::getNumberOfEdges() const { int edges = 0; for (auto i = 0; i < n_models; ++i) { @@ -128,7 +128,7 @@ namespace bayesnet { } return edges; } - int Ensemble::getNumberOfStates() + int Ensemble::getNumberOfStates() const { int nstates = 0; for (auto i = 0; i < n_models; ++i) { diff --git a/src/BayesNet/Ensemble.h b/src/BayesNet/Ensemble.h index f36d1ad..f0d750b 100644 --- a/src/BayesNet/Ensemble.h +++ b/src/BayesNet/Ensemble.h @@ -23,16 +23,16 @@ namespace bayesnet { vector predict(vector>& X) override; float score(Tensor& X, Tensor& y) override; float score(vector>& X, vector& y) override; - int getNumberOfNodes() override; - int getNumberOfEdges() override; - int getNumberOfStates() override; - vector show() override; - vector graph(const string& title) override; - vector topological_order() override + int getNumberOfNodes() const override; + int getNumberOfEdges() const override; + int getNumberOfStates() const override; + vector show() const override; + vector graph(const string& title) const override; + vector topological_order() override { return vector(); } - void dump_cpt() override + void dump_cpt() const override { } }; diff --git a/src/BayesNet/KDB.cc b/src/BayesNet/KDB.cc index 6988671..74566b0 100644 --- a/src/BayesNet/KDB.cc +++ b/src/BayesNet/KDB.cc @@ -79,7 +79,7 @@ namespace bayesnet { exit_cond = num == n_edges || candidates.size(0) == 0; } } - vector KDB::graph(const string& title) + vector KDB::graph(const string& title) const { string header{ title }; if (title == "KDB") { diff --git a/src/BayesNet/KDB.h b/src/BayesNet/KDB.h index 028bee8..e7af8c5 100644 --- a/src/BayesNet/KDB.h +++ b/src/BayesNet/KDB.h @@ -15,7 +15,7 @@ namespace bayesnet { public: explicit KDB(int k, float theta = 0.03); virtual ~KDB() {}; - vector graph(const string& name = "KDB") override; + vector graph(const string& name = "KDB") const override; }; } #endif \ No newline at end of file diff --git a/src/BayesNet/KDBLd.cc b/src/BayesNet/KDBLd.cc index 63344af..4b8b91c 100644 --- a/src/BayesNet/KDBLd.cc +++ b/src/BayesNet/KDBLd.cc @@ -23,7 +23,7 @@ namespace bayesnet { auto Xt = prepareX(X); return KDB::predict(Xt); } - vector KDBLd::graph(const string& name) + vector KDBLd::graph(const string& name) const { return KDB::graph(name); } diff --git a/src/BayesNet/KDBLd.h b/src/BayesNet/KDBLd.h index b91999b..50a1b95 100644 --- a/src/BayesNet/KDBLd.h +++ b/src/BayesNet/KDBLd.h @@ -11,7 +11,7 @@ namespace bayesnet { explicit KDBLd(int k); virtual ~KDBLd() = default; KDBLd& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; - vector graph(const string& name = "KDB") override; + vector graph(const string& name = "KDB") const override; Tensor predict(Tensor& X) override; static inline string version() { return "0.0.1"; }; }; diff --git a/src/BayesNet/Network.cc b/src/BayesNet/Network.cc index 5b6307a..59903f3 100644 --- a/src/BayesNet/Network.cc +++ b/src/BayesNet/Network.cc @@ -43,15 +43,15 @@ namespace bayesnet { } nodes[name] = std::make_unique(name); } - vector Network::getFeatures() + vector Network::getFeatures() const { return features; } - int Network::getClassNumStates() + int Network::getClassNumStates() const { return classNumStates; } - int Network::getStates() + int Network::getStates() const { int result = 0; for (auto& node : nodes) { @@ -59,7 +59,7 @@ namespace bayesnet { } return result; } - string Network::getClassName() + string Network::getClassName() const { return className; } @@ -343,7 +343,7 @@ namespace bayesnet { transform(result.begin(), result.end(), result.begin(), [sum](double& value) { return value / sum; }); return result; } - vector Network::show() + vector Network::show() const { vector result; // Draw the network @@ -356,7 +356,7 @@ namespace bayesnet { } return result; } - vector Network::graph(const string& title) + vector Network::graph(const string& title) const { auto output = vector(); auto prefix = "digraph BayesNet {\nlabel=> Network::getEdges() + vector> Network::getEdges() const { auto edges = vector>(); for (const auto& node : nodes) { @@ -382,6 +382,10 @@ namespace bayesnet { } return edges; } + int Network::getNumEdges() const + { + return getEdges().size(); + } vector Network::topological_sort() { /* Check if al the fathers of every node are before the node */ @@ -420,7 +424,7 @@ namespace bayesnet { } return result; } - void Network::dump_cpt() + void Network::dump_cpt() const { for (auto& node : nodes) { cout << "* " << node.first << ": (" << node.second->getNumStates() << ") : " << node.second->getCPT().sizes() << endl; diff --git a/src/BayesNet/Network.h b/src/BayesNet/Network.h index 616235a..eb65957 100644 --- a/src/BayesNet/Network.h +++ b/src/BayesNet/Network.h @@ -37,11 +37,12 @@ namespace bayesnet { void addNode(const string&); void addEdge(const string&, const string&); map>& getNodes(); - vector getFeatures(); - int getStates(); - vector> getEdges(); - int getClassNumStates(); - string getClassName(); + vector getFeatures() const; + int getStates() const; + vector> getEdges() const; + int getNumEdges() const; + int getClassNumStates() const; + string getClassName() const; void fit(const vector>&, const vector&, const vector&, const string&); void fit(const torch::Tensor&, const torch::Tensor&, const vector&, const string&); void fit(const torch::Tensor&, const vector&, const string&); @@ -54,10 +55,10 @@ namespace bayesnet { torch::Tensor predict_proba(const torch::Tensor&); // Return mxn tensor of probabilities double score(const vector>&, const vector&); vector topological_sort(); - vector show(); - vector graph(const string& title); // Returns a vector of strings representing the graph in graphviz format + vector show() const; + vector graph(const string& title) const; // Returns a vector of strings representing the graph in graphviz format void initialize(); - void dump_cpt(); + void dump_cpt() const; inline string version() { return "0.1.0"; } }; } diff --git a/src/BayesNet/Proposal.cc b/src/BayesNet/Proposal.cc index 19992c6..80cb7ee 100644 --- a/src/BayesNet/Proposal.cc +++ b/src/BayesNet/Proposal.cc @@ -2,7 +2,7 @@ #include "ArffFiles.h" namespace bayesnet { - Proposal::Proposal(torch::Tensor& dataset_, vector& features_, string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_), m(dataset_.size(1)), n(dataset_.size(0) - 1) {} + Proposal::Proposal(torch::Tensor& dataset_, vector& features_, string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_) {} Proposal::~Proposal() { for (auto& [key, value] : discretizers) { @@ -32,9 +32,9 @@ namespace bayesnet { indices.push_back(-1); // Add class index transform(parents.begin(), parents.end(), back_inserter(indices), [&](const auto& p) {return find(pFeatures.begin(), pFeatures.end(), p) - pFeatures.begin(); }); // Now we fit the discretizer of the feature, conditioned on its parents and the class i.e. discretizer.fit(X[index], X[indices] + y) - vector yJoinParents(indices.size()); + vector yJoinParents(Xf.size(1)); for (auto idx : indices) { - for (int i = 0; i < n; ++i) { + for (int i = 0; i < Xf.size(1); ++i) { yJoinParents[i] += to_string(pDataset.index({ idx, i }).item()); } } @@ -64,10 +64,13 @@ namespace bayesnet { //Update new states of the feature/node states[pFeatures[index]] = xStates; } + model.fit(pDataset, pFeatures, pClassName); } } void Proposal::fit_local_discretization(map>& states, torch::Tensor& y) { + int m = Xf.size(1); + int n = Xf.size(0); pDataset = torch::zeros({ n + 1, m }, kInt32); auto yv = vector(y.data_ptr(), y.data_ptr() + y.size(0)); // discretize input data by feature(row) diff --git a/src/BayesNet/Proposal.h b/src/BayesNet/Proposal.h index 606ed5a..06d9dd6 100644 --- a/src/BayesNet/Proposal.h +++ b/src/BayesNet/Proposal.h @@ -19,7 +19,6 @@ namespace bayesnet { torch::Tensor Xf; // X continuous nxm tensor torch::Tensor y; // y discrete nx1 tensor map discretizers; - int m, n; private: torch::Tensor& pDataset; // (n+1)xm tensor vector& pFeatures; diff --git a/src/BayesNet/SPODE.cc b/src/BayesNet/SPODE.cc index eba6542..a90e5ef 100644 --- a/src/BayesNet/SPODE.cc +++ b/src/BayesNet/SPODE.cc @@ -17,7 +17,7 @@ namespace bayesnet { } } } - vector SPODE::graph(const string& name) + vector SPODE::graph(const string& name) const { return model.graph(name); } diff --git a/src/BayesNet/SPODE.h b/src/BayesNet/SPODE.h index d441e66..f9b6af0 100644 --- a/src/BayesNet/SPODE.h +++ b/src/BayesNet/SPODE.h @@ -11,7 +11,7 @@ namespace bayesnet { public: explicit SPODE(int root); virtual ~SPODE() {}; - vector graph(const string& name = "SPODE") override; + vector graph(const string& name = "SPODE") const override; }; } #endif \ No newline at end of file diff --git a/src/BayesNet/SPODELd.cc b/src/BayesNet/SPODELd.cc index 8b9fe2f..8c47df1 100644 --- a/src/BayesNet/SPODELd.cc +++ b/src/BayesNet/SPODELd.cc @@ -2,10 +2,11 @@ namespace bayesnet { using namespace std; - SPODELd::SPODELd(int root) : SPODE(root), Proposal(dataset, features, className) {} + SPODELd::SPODELd(int root) : SPODE(root), Proposal(dataset, features, className) { cout << "SPODELd constructor" << endl; } SPODELd& SPODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { // This first part should go in a Classifier method called fit_local_discretization o fit_float... + cout << "YOOOOOOOOOOOOOOOOOOOo" << endl; features = features_; className = className_; Xf = X_; @@ -16,7 +17,6 @@ namespace bayesnet { // 1st we need to fit the model to build the normal SPODE structure, SPODE::fit initializes the base Bayesian network SPODE::fit(dataset, features, className, states); localDiscretizationProposal(states, model); - //model.fit(SPODE::Xv, SPODE::yv, features, className); return *this; } Tensor SPODELd::predict(Tensor& X) @@ -24,7 +24,11 @@ namespace bayesnet { auto Xt = prepareX(X); return SPODE::predict(Xt); } - vector SPODELd::graph(const string& name) + void SPODELd::test() + { + cout << "SPODELd test" << endl; + } + vector SPODELd::graph(const string& name) const { return SPODE::graph(name); } diff --git a/src/BayesNet/SPODELd.h b/src/BayesNet/SPODELd.h index 789af7f..f949c09 100644 --- a/src/BayesNet/SPODELd.h +++ b/src/BayesNet/SPODELd.h @@ -6,12 +6,12 @@ namespace bayesnet { using namespace std; class SPODELd : public SPODE, public Proposal { - private: public: + void test(); explicit SPODELd(int root); virtual ~SPODELd() = default; SPODELd& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; - vector graph(const string& name = "SPODE") override; + vector graph(const string& name = "SPODE") const override; Tensor predict(Tensor& X) override; static inline string version() { return "0.0.1"; }; }; diff --git a/src/BayesNet/TAN.cc b/src/BayesNet/TAN.cc index c77275c..7b3e3a6 100644 --- a/src/BayesNet/TAN.cc +++ b/src/BayesNet/TAN.cc @@ -34,7 +34,7 @@ namespace bayesnet { model.addEdge(className, feature); } } - vector TAN::graph(const string& title) + vector TAN::graph(const string& title) const { return model.graph(title); } diff --git a/src/BayesNet/TAN.h b/src/BayesNet/TAN.h index 6d95e21..4c1c5f5 100644 --- a/src/BayesNet/TAN.h +++ b/src/BayesNet/TAN.h @@ -11,7 +11,7 @@ namespace bayesnet { public: TAN(); virtual ~TAN() {}; - vector graph(const string& name = "TAN") override; + vector graph(const string& name = "TAN") const override; }; } #endif \ No newline at end of file diff --git a/src/BayesNet/TANLd.cc b/src/BayesNet/TANLd.cc index 49ffa96..dba803c 100644 --- a/src/BayesNet/TANLd.cc +++ b/src/BayesNet/TANLd.cc @@ -16,15 +16,15 @@ namespace bayesnet { // 1st we need to fit the model to build the normal TAN structure, TAN::fit initializes the base Bayesian network TAN::fit(dataset, features, className, states); localDiscretizationProposal(states, model); - //model.fit(dataset, features, className); return *this; + } Tensor TANLd::predict(Tensor& X) { auto Xt = prepareX(X); return TAN::predict(Xt); } - vector TANLd::graph(const string& name) + vector TANLd::graph(const string& name) const { return TAN::graph(name); } diff --git a/src/BayesNet/TANLd.h b/src/BayesNet/TANLd.h index d9172ac..c35e843 100644 --- a/src/BayesNet/TANLd.h +++ b/src/BayesNet/TANLd.h @@ -11,7 +11,7 @@ namespace bayesnet { TANLd(); virtual ~TANLd() = default; TANLd& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; - vector graph(const string& name = "TAN") override; + vector graph(const string& name = "TAN") const override; Tensor predict(Tensor& X) override; static inline string version() { return "0.0.1"; }; }; -- 2.45.2 From 0ad5505c16a7b958f9c45a66194cafb43ad47f4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Monta=C3=B1ana?= Date: Thu, 10 Aug 2023 02:06:18 +0200 Subject: [PATCH 4/6] Spodeld working with poor accuracy --- src/BayesNet/AODELd.cc | 11 ++--------- src/BayesNet/SPODELd.cc | 24 ++++++++++++++++++------ src/BayesNet/SPODELd.h | 2 +- 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/BayesNet/AODELd.cc b/src/BayesNet/AODELd.cc index 8a656cc..fbfaefd 100644 --- a/src/BayesNet/AODELd.cc +++ b/src/BayesNet/AODELd.cc @@ -22,22 +22,15 @@ namespace bayesnet { void AODELd::buildModel() { models.clear(); - cout << "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!" << endl; for (int i = 0; i < features.size(); ++i) { - models.push_back(Models::instance().create("SPODELd")); - models[i]->test(); + models.push_back(std::make_unique(i)); } n_models = models.size(); } void AODELd::trainModel() { - cout << "dataset: " << dataset.sizes() << endl; - cout << "features: " << features.size() << endl; - cout << "className: " << className << endl; - cout << "states: " << states.size() << endl; for (const auto& model : models) { - model->fit(dataset, features, className, states); - model->test(); + model->fit(Xf, y, features, className, states); } } vector AODELd::graph(const string& name) const diff --git a/src/BayesNet/SPODELd.cc b/src/BayesNet/SPODELd.cc index 8c47df1..0e58775 100644 --- a/src/BayesNet/SPODELd.cc +++ b/src/BayesNet/SPODELd.cc @@ -2,11 +2,10 @@ namespace bayesnet { using namespace std; - SPODELd::SPODELd(int root) : SPODE(root), Proposal(dataset, features, className) { cout << "SPODELd constructor" << endl; } + SPODELd::SPODELd(int root) : SPODE(root), Proposal(dataset, features, className) {} SPODELd& SPODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector& features_, string className_, map>& states_) { // This first part should go in a Classifier method called fit_local_discretization o fit_float... - cout << "YOOOOOOOOOOOOOOOOOOOo" << endl; features = features_; className = className_; Xf = X_; @@ -19,15 +18,28 @@ namespace bayesnet { localDiscretizationProposal(states, model); return *this; } + SPODELd& SPODELd::fit(torch::Tensor& dataset, vector& features_, string className_, map>& states_) + { + Xf = dataset.index({ torch::indexing::Slice(0, dataset.size(0) - 1), "..." }).clone(); + cout << "Xf " << Xf.sizes() << " dtype: " << Xf.dtype() << endl; + y = dataset.index({ -1, "..." }).clone(); + // This first part should go in a Classifier method called fit_local_discretization o fit_float... + features = features_; + className = className_; + // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y + fit_local_discretization(states, y); + // We have discretized the input data + // 1st we need to fit the model to build the normal SPODE structure, SPODE::fit initializes the base Bayesian network + SPODE::fit(dataset, features, className, states); + localDiscretizationProposal(states, model); + return *this; + } + Tensor SPODELd::predict(Tensor& X) { auto Xt = prepareX(X); return SPODE::predict(Xt); } - void SPODELd::test() - { - cout << "SPODELd test" << endl; - } vector SPODELd::graph(const string& name) const { return SPODE::graph(name); diff --git a/src/BayesNet/SPODELd.h b/src/BayesNet/SPODELd.h index f949c09..b94fc6c 100644 --- a/src/BayesNet/SPODELd.h +++ b/src/BayesNet/SPODELd.h @@ -7,10 +7,10 @@ namespace bayesnet { using namespace std; class SPODELd : public SPODE, public Proposal { public: - void test(); explicit SPODELd(int root); virtual ~SPODELd() = default; SPODELd& fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) override; + SPODELd& fit(torch::Tensor& dataset, vector& features, string className, map>& states) override; vector graph(const string& name = "SPODE") const override; Tensor predict(Tensor& X) override; static inline string version() { return "0.0.1"; }; -- 2.45.2 From 3a85481a5acde0463bf3c1ebd424d9613eda7d40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Montan=CC=83ana?= Date: Sat, 12 Aug 2023 11:10:53 +0200 Subject: [PATCH 5/6] Redo pass states to Network Fit needed in crossval fix mistake in headerline (report) --- .vscode/launch.json | 4 ++-- src/BayesNet/Classifier.cc | 2 +- src/BayesNet/Network.cc | 33 ++++++++++++++++++--------------- src/BayesNet/Network.h | 18 ++++++------------ src/BayesNet/Proposal.cc | 2 +- src/Platform/Report.cc | 5 +++-- 6 files changed, 31 insertions(+), 33 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 7241ae2..e3c35bb 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -25,12 +25,12 @@ "program": "${workspaceFolder}/build/src/Platform/main", "args": [ "-m", - "AODELd", + "TANLd", "-p", "/Users/rmontanana/Code/discretizbench/datasets", "--stratified", "-d", - "iris" + "vehicle" ], "cwd": "/Users/rmontanana/Code/discretizbench", }, diff --git a/src/BayesNet/Classifier.cc b/src/BayesNet/Classifier.cc index 7f41839..b3317f4 100644 --- a/src/BayesNet/Classifier.cc +++ b/src/BayesNet/Classifier.cc @@ -37,7 +37,7 @@ namespace bayesnet { } void Classifier::trainModel() { - model.fit(dataset, features, className); + model.fit(dataset, features, className, states); } // X is nxm where n is the number of features and m the number of samples Classifier& Classifier::fit(torch::Tensor& X, torch::Tensor& y, vector& features, string className, map>& states) diff --git a/src/BayesNet/Network.cc b/src/BayesNet/Network.cc index 59903f3..8a4106c 100644 --- a/src/BayesNet/Network.cc +++ b/src/BayesNet/Network.cc @@ -104,7 +104,7 @@ namespace bayesnet { { return nodes; } - void Network::checkFitData(int n_samples, int n_features, int n_samples_y, const vector& featureNames, const string& className) + void Network::checkFitData(int n_samples, int n_features, int n_samples_y, const vector& featureNames, const string& className, const map>& states) { if (n_samples != n_samples_y) { throw invalid_argument("X and y must have the same number of samples in Network::fit (" + to_string(n_samples) + " != " + to_string(n_samples_y) + ")"); @@ -122,39 +122,42 @@ namespace bayesnet { if (find(features.begin(), features.end(), feature) == features.end()) { throw invalid_argument("Feature " + feature + " not found in Network::features"); } + if (states.find(feature) == states.end()) { + throw invalid_argument("Feature " + feature + " not found in states"); + } } } - void Network::setStates() + void Network::setStates(const map>& states) { // Set states to every Node in the network for (int i = 0; i < features.size(); ++i) { - nodes[features[i]]->setNumStates(static_cast(torch::max(samples.index({ i, "..." })).item()) + 1); + nodes[features[i]]->setNumStates(states.at(features[i]).size()); } classNumStates = nodes[className]->getNumStates(); } // X comes in nxm, where n is the number of features and m the number of samples - void Network::fit(const torch::Tensor& X, const torch::Tensor& y, const vector& featureNames, const string& className) + void Network::fit(const torch::Tensor& X, const torch::Tensor& y, const vector& featureNames, const string& className, const map>& states) { - checkFitData(X.size(1), X.size(0), y.size(0), featureNames, className); + checkFitData(X.size(1), X.size(0), y.size(0), featureNames, className, states); this->className = className; Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); samples = torch::cat({ X , ytmp }, 0); for (int i = 0; i < featureNames.size(); ++i) { auto row_feature = X.index({ i, "..." }); } - completeFit(); + completeFit(states); } - void Network::fit(const torch::Tensor& samples, const vector& featureNames, const string& className) + void Network::fit(const torch::Tensor& samples, const vector& featureNames, const string& className, const map>& states) { - checkFitData(samples.size(1), samples.size(0) - 1, samples.size(1), featureNames, className); + checkFitData(samples.size(1), samples.size(0) - 1, samples.size(1), featureNames, className, states); this->className = className; this->samples = samples; - completeFit(); + completeFit(states); } // input_data comes in nxm, where n is the number of features and m the number of samples - void Network::fit(const vector>& input_data, const vector& labels, const vector& featureNames, const string& className) + void Network::fit(const vector>& input_data, const vector& labels, const vector& featureNames, const string& className, const map>& states) { - checkFitData(input_data[0].size(), input_data.size(), labels.size(), featureNames, className); + checkFitData(input_data[0].size(), input_data.size(), labels.size(), featureNames, className, states); this->className = className; // Build tensor of samples (nxm) (n+1 because of the class) samples = torch::zeros({ static_cast(input_data.size() + 1), static_cast(input_data[0].size()) }, torch::kInt32); @@ -162,11 +165,11 @@ namespace bayesnet { samples.index_put_({ i, "..." }, torch::tensor(input_data[i], torch::kInt32)); } samples.index_put_({ -1, "..." }, torch::tensor(labels, torch::kInt32)); - completeFit(); + completeFit(states); } - void Network::completeFit() + void Network::completeFit(const map>& states) { - setStates(); + setStates(states); int maxThreadsRunning = static_cast(std::thread::hardware_concurrency() * maxThreads); if (maxThreadsRunning < 1) { maxThreadsRunning = 1; @@ -212,7 +215,7 @@ namespace bayesnet { torch::Tensor result; result = torch::zeros({ samples.size(1), classNumStates }, torch::kFloat64); for (int i = 0; i < samples.size(1); ++i) { - auto sample = samples.index({ "...", i }); + const Tensor sample = samples.index({ "...", i }); auto psample = predict_sample(sample); auto temp = torch::tensor(psample, torch::kFloat64); // result.index_put_({ i, "..." }, torch::tensor(predict_sample(sample), torch::kFloat64)); diff --git a/src/BayesNet/Network.h b/src/BayesNet/Network.h index eb65957..d8db620 100644 --- a/src/BayesNet/Network.h +++ b/src/BayesNet/Network.h @@ -20,13 +20,9 @@ namespace bayesnet { vector predict_sample(const torch::Tensor&); vector exactInference(map&); double computeFactor(map&); - double mutual_info(torch::Tensor&, torch::Tensor&); - double entropy(torch::Tensor&); - double conditionalEntropy(torch::Tensor&, torch::Tensor&); - double mutualInformation(torch::Tensor&, torch::Tensor&); - void completeFit(); - void checkFitData(int n_features, int n_samples, int n_samples_y, const vector& featureNames, const string& className); - void setStates(); + void completeFit(const map>&); + void checkFitData(int n_features, int n_samples, int n_samples_y, const vector& featureNames, const string& className, const map>&); + void setStates(const map>&); public: Network(); explicit Network(float, int); @@ -43,13 +39,11 @@ namespace bayesnet { int getNumEdges() const; int getClassNumStates() const; string getClassName() const; - void fit(const vector>&, const vector&, const vector&, const string&); - void fit(const torch::Tensor&, const torch::Tensor&, const vector&, const string&); - void fit(const torch::Tensor&, const vector&, const string&); + void fit(const vector>&, const vector&, const vector&, const string&, const map>&); + void fit(const torch::Tensor&, const torch::Tensor&, const vector&, const string&, const map>&); + void fit(const torch::Tensor&, const vector&, const string&, const map>&); vector predict(const vector>&); // Return mx1 vector of predictions torch::Tensor predict(const torch::Tensor&); // Return mx1 tensor of predictions - //Computes the conditional edge weight of variable index u and v conditioned on class_node - torch::Tensor conditionalEdgeWeight(); torch::Tensor predict_tensor(const torch::Tensor& samples, const bool proba); vector> predict_proba(const vector>&); // Return mxn vector of probabilities torch::Tensor predict_proba(const torch::Tensor&); // Return mxn tensor of probabilities diff --git a/src/BayesNet/Proposal.cc b/src/BayesNet/Proposal.cc index 80cb7ee..78d5225 100644 --- a/src/BayesNet/Proposal.cc +++ b/src/BayesNet/Proposal.cc @@ -64,7 +64,7 @@ namespace bayesnet { //Update new states of the feature/node states[pFeatures[index]] = xStates; } - model.fit(pDataset, pFeatures, pClassName); + model.fit(pDataset, pFeatures, pClassName, states); } } void Proposal::fit_local_discretization(map>& states, torch::Tensor& y) diff --git a/src/Platform/Report.cc b/src/Platform/Report.cc index 90aad2b..3693248 100644 --- a/src/Platform/Report.cc +++ b/src/Platform/Report.cc @@ -4,6 +4,7 @@ namespace platform { string headerLine(const string& text) { int n = MAXL - text.length() - 3; + n = n < 0 ? 0 : n; return "* " + text + string(n, ' ') + "*\n"; } string Report::fromVector(const string& key) @@ -13,7 +14,7 @@ namespace platform { for (auto& item : data[key]) { result += to_string(item) + ", "; } - return "[" + result.substr(0, result.length() - 2) + "]"; + return "[" + result.substr(0, result.size() - 2) + "]"; } string fVector(const json& data) { @@ -21,7 +22,7 @@ namespace platform { for (const auto& item : data) { result += to_string(item) + ", "; } - return "[" + result.substr(0, result.length() - 2) + "]"; + return "[" + result.substr(0, result.size() - 2) + "]"; } void Report::show() { -- 2.45.2 From 405887f83393b842500e01000f8b886847cc94cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Montan=CC=83ana?= Date: Sat, 12 Aug 2023 11:49:18 +0200 Subject: [PATCH 6/6] Solved Ld poor results --- .vscode/launch.json | 4 ++-- src/BayesNet/AODELd.cc | 2 +- src/BayesNet/KDBLd.cc | 2 +- src/BayesNet/Proposal.cc | 6 +++++- src/BayesNet/Proposal.h | 2 +- src/BayesNet/SPODELd.cc | 4 ++-- src/BayesNet/TANLd.cc | 2 +- 7 files changed, 13 insertions(+), 9 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index e3c35bb..ba01ca6 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -25,12 +25,12 @@ "program": "${workspaceFolder}/build/src/Platform/main", "args": [ "-m", - "TANLd", + "SPODELd", "-p", "/Users/rmontanana/Code/discretizbench/datasets", "--stratified", "-d", - "vehicle" + "iris" ], "cwd": "/Users/rmontanana/Code/discretizbench", }, diff --git a/src/BayesNet/AODELd.cc b/src/BayesNet/AODELd.cc index fbfaefd..9f36ed2 100644 --- a/src/BayesNet/AODELd.cc +++ b/src/BayesNet/AODELd.cc @@ -12,7 +12,7 @@ namespace bayesnet { Xf = X_; y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y - fit_local_discretization(states, y); + states = fit_local_discretization(y); // We have discretized the input data // 1st we need to fit the model to build the normal TAN structure, TAN::fit initializes the base Bayesian network Ensemble::fit(dataset, features, className, states); diff --git a/src/BayesNet/KDBLd.cc b/src/BayesNet/KDBLd.cc index 4b8b91c..724a053 100644 --- a/src/BayesNet/KDBLd.cc +++ b/src/BayesNet/KDBLd.cc @@ -11,7 +11,7 @@ namespace bayesnet { Xf = X_; y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y - fit_local_discretization(states, y); + states = fit_local_discretization(y); // We have discretized the input data // 1st we need to fit the model to build the normal KDB structure, KDB::fit initializes the base Bayesian network KDB::fit(dataset, features, className, states); diff --git a/src/BayesNet/Proposal.cc b/src/BayesNet/Proposal.cc index 78d5225..d53094d 100644 --- a/src/BayesNet/Proposal.cc +++ b/src/BayesNet/Proposal.cc @@ -67,10 +67,12 @@ namespace bayesnet { model.fit(pDataset, pFeatures, pClassName, states); } } - void Proposal::fit_local_discretization(map>& states, torch::Tensor& y) + map> Proposal::fit_local_discretization(torch::Tensor& y) { + // Discretize the continuous input data and build pDataset (Classifier::dataset) int m = Xf.size(1); int n = Xf.size(0); + map> states; pDataset = torch::zeros({ n + 1, m }, kInt32); auto yv = vector(y.data_ptr(), y.data_ptr() + y.size(0)); // discretize input data by feature(row) @@ -89,6 +91,8 @@ namespace bayesnet { auto yStates = vector(n_classes); iota(yStates.begin(), yStates.end(), 0); states[pClassName] = yStates; + pDataset.index_put_({ n, "..." }, y); + return states; } torch::Tensor Proposal::prepareX(torch::Tensor& X) { diff --git a/src/BayesNet/Proposal.h b/src/BayesNet/Proposal.h index 06d9dd6..10814c2 100644 --- a/src/BayesNet/Proposal.h +++ b/src/BayesNet/Proposal.h @@ -15,7 +15,7 @@ namespace bayesnet { protected: torch::Tensor prepareX(torch::Tensor& X); void localDiscretizationProposal(map>& states, Network& model); - void fit_local_discretization(map>& states, torch::Tensor& y); + map> fit_local_discretization(torch::Tensor& y); torch::Tensor Xf; // X continuous nxm tensor torch::Tensor y; // y discrete nx1 tensor map discretizers; diff --git a/src/BayesNet/SPODELd.cc b/src/BayesNet/SPODELd.cc index 0e58775..9683b7e 100644 --- a/src/BayesNet/SPODELd.cc +++ b/src/BayesNet/SPODELd.cc @@ -11,7 +11,7 @@ namespace bayesnet { Xf = X_; y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y - fit_local_discretization(states, y); + states = fit_local_discretization(y); // We have discretized the input data // 1st we need to fit the model to build the normal SPODE structure, SPODE::fit initializes the base Bayesian network SPODE::fit(dataset, features, className, states); @@ -27,7 +27,7 @@ namespace bayesnet { features = features_; className = className_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y - fit_local_discretization(states, y); + states = fit_local_discretization(y); // We have discretized the input data // 1st we need to fit the model to build the normal SPODE structure, SPODE::fit initializes the base Bayesian network SPODE::fit(dataset, features, className, states); diff --git a/src/BayesNet/TANLd.cc b/src/BayesNet/TANLd.cc index dba803c..a30cba8 100644 --- a/src/BayesNet/TANLd.cc +++ b/src/BayesNet/TANLd.cc @@ -11,7 +11,7 @@ namespace bayesnet { Xf = X_; y = y_; // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y - fit_local_discretization(states, y); + states = fit_local_discretization(y); // We have discretized the input data // 1st we need to fit the model to build the normal TAN structure, TAN::fit initializes the base Bayesian network TAN::fit(dataset, features, className, states); -- 2.45.2