Compare commits
11 Commits
45c1d052ac
...
TANNew
Author | SHA1 | Date | |
---|---|---|---|
2da0fb5d8f
|
|||
14ea51648a
|
|||
9e94f4e140
|
|||
1d0fd629c9
|
|||
506ef34c6f
|
|||
7f45495837
|
|||
1a09ccca4c
|
|||
a1c6ab18f3
|
|||
64ac8fb4f2
|
|||
c568ba111d
|
|||
a9ba21560d
|
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
@@ -25,14 +25,14 @@
|
||||
"program": "${workspaceFolder}/build/src/Platform/main",
|
||||
"args": [
|
||||
"-m",
|
||||
"TANNew",
|
||||
"AODELd",
|
||||
"-p",
|
||||
"/Users/rmontanana/Code/discretizbench/datasets",
|
||||
"--stratified",
|
||||
"-d",
|
||||
"iris"
|
||||
],
|
||||
"cwd": "${workspaceFolder}/build/src/Platform",
|
||||
"cwd": "/Users/rmontanana/Code/discretizbench",
|
||||
},
|
||||
{
|
||||
"name": "Build & debug active file",
|
||||
|
8
Makefile
8
Makefile
@@ -14,6 +14,14 @@ setup: ## Install dependencies for tests and coverage
|
||||
dependency: ## Create a dependency graph diagram of the project (build/dependency.png)
|
||||
cd build && cmake .. --graphviz=dependency.dot && dot -Tpng dependency.dot -o dependency.png
|
||||
|
||||
build: ## Build the main and BayesNetSample
|
||||
cmake --build build -t main -t BayesNetSample -j 32
|
||||
|
||||
clean: ## Clean the debug info
|
||||
@echo ">>> Cleaning Debug BayesNet ...";
|
||||
find . -name "*.gcda" -print0 | xargs -0 rm
|
||||
@echo ">>> Done";
|
||||
|
||||
debug: ## Build a debug version of the project
|
||||
@echo ">>> Building Debug BayesNet ...";
|
||||
@if [ -d ./build ]; then rm -rf ./build; fi
|
||||
|
112
sample/sample.cc
112
sample/sample.cc
@@ -178,61 +178,59 @@ int main(int argc, char** argv)
|
||||
cout << "end." << endl;
|
||||
auto score = clf->score(Xd, y);
|
||||
cout << "Score: " << score << endl;
|
||||
auto graph = clf->graph();
|
||||
auto dot_file = model_name + "_" + file_name;
|
||||
ofstream file(dot_file + ".dot");
|
||||
file << graph;
|
||||
file.close();
|
||||
cout << "Graph saved in " << model_name << "_" << file_name << ".dot" << endl;
|
||||
cout << "dot -Tpng -o " + dot_file + ".png " + dot_file + ".dot " << endl;
|
||||
string stratified_string = stratified ? " Stratified" : "";
|
||||
cout << nFolds << " Folds" << stratified_string << " Cross validation" << endl;
|
||||
cout << "==========================================" << endl;
|
||||
torch::Tensor Xt = torch::zeros({ static_cast<int>(Xd.size()), static_cast<int>(Xd[0].size()) }, torch::kInt32);
|
||||
torch::Tensor yt = torch::tensor(y, torch::kInt32);
|
||||
for (int i = 0; i < features.size(); ++i) {
|
||||
Xt.index_put_({ i, "..." }, torch::tensor(Xd[i], torch::kInt32));
|
||||
}
|
||||
float total_score = 0, total_score_train = 0, score_train, score_test;
|
||||
Fold* fold;
|
||||
if (stratified)
|
||||
fold = new StratifiedKFold(nFolds, y, seed);
|
||||
else
|
||||
fold = new KFold(nFolds, y.size(), seed);
|
||||
for (auto i = 0; i < nFolds; ++i) {
|
||||
auto [train, test] = fold->getFold(i);
|
||||
cout << "Fold: " << i + 1 << endl;
|
||||
if (tensors) {
|
||||
auto ttrain = torch::tensor(train, torch::kInt64);
|
||||
auto ttest = torch::tensor(test, torch::kInt64);
|
||||
torch::Tensor Xtraint = torch::index_select(Xt, 1, ttrain);
|
||||
torch::Tensor ytraint = yt.index({ ttrain });
|
||||
torch::Tensor Xtestt = torch::index_select(Xt, 1, ttest);
|
||||
torch::Tensor ytestt = yt.index({ ttest });
|
||||
clf->fit(Xtraint, ytraint, features, className, states);
|
||||
auto temp = clf->predict(Xtraint);
|
||||
score_train = clf->score(Xtraint, ytraint);
|
||||
score_test = clf->score(Xtestt, ytestt);
|
||||
} else {
|
||||
auto [Xtrain, ytrain] = extract_indices(train, Xd, y);
|
||||
auto [Xtest, ytest] = extract_indices(test, Xd, y);
|
||||
clf->fit(Xtrain, ytrain, features, className, states);
|
||||
|
||||
score_train = clf->score(Xtrain, ytrain);
|
||||
score_test = clf->score(Xtest, ytest);
|
||||
}
|
||||
if (dump_cpt) {
|
||||
cout << "--- CPT Tables ---" << endl;
|
||||
clf->dump_cpt();
|
||||
}
|
||||
total_score_train += score_train;
|
||||
total_score += score_test;
|
||||
cout << "Score Train: " << score_train << endl;
|
||||
cout << "Score Test : " << score_test << endl;
|
||||
cout << "-------------------------------------------------------------------------------" << endl;
|
||||
}
|
||||
cout << "**********************************************************************************" << endl;
|
||||
cout << "Average Score Train: " << total_score_train / nFolds << endl;
|
||||
cout << "Average Score Test : " << total_score / nFolds << endl;
|
||||
return 0;
|
||||
// auto graph = clf->graph();
|
||||
// auto dot_file = model_name + "_" + file_name;
|
||||
// ofstream file(dot_file + ".dot");
|
||||
// file << graph;
|
||||
// file.close();
|
||||
// cout << "Graph saved in " << model_name << "_" << file_name << ".dot" << endl;
|
||||
// cout << "dot -Tpng -o " + dot_file + ".png " + dot_file + ".dot " << endl;
|
||||
// string stratified_string = stratified ? " Stratified" : "";
|
||||
// cout << nFolds << " Folds" << stratified_string << " Cross validation" << endl;
|
||||
// cout << "==========================================" << endl;
|
||||
// torch::Tensor Xt = torch::zeros({ static_cast<int>(Xd.size()), static_cast<int>(Xd[0].size()) }, torch::kInt32);
|
||||
// torch::Tensor yt = torch::tensor(y, torch::kInt32);
|
||||
// for (int i = 0; i < features.size(); ++i) {
|
||||
// Xt.index_put_({ i, "..." }, torch::tensor(Xd[i], torch::kInt32));
|
||||
// }
|
||||
// float total_score = 0, total_score_train = 0, score_train, score_test;
|
||||
// Fold* fold;
|
||||
// if (stratified)
|
||||
// fold = new StratifiedKFold(nFolds, y, seed);
|
||||
// else
|
||||
// fold = new KFold(nFolds, y.size(), seed);
|
||||
// for (auto i = 0; i < nFolds; ++i) {
|
||||
// auto [train, test] = fold->getFold(i);
|
||||
// cout << "Fold: " << i + 1 << endl;
|
||||
// if (tensors) {
|
||||
// auto ttrain = torch::tensor(train, torch::kInt64);
|
||||
// auto ttest = torch::tensor(test, torch::kInt64);
|
||||
// torch::Tensor Xtraint = torch::index_select(Xt, 1, ttrain);
|
||||
// torch::Tensor ytraint = yt.index({ ttrain });
|
||||
// torch::Tensor Xtestt = torch::index_select(Xt, 1, ttest);
|
||||
// torch::Tensor ytestt = yt.index({ ttest });
|
||||
// clf->fit(Xtraint, ytraint, features, className, states);
|
||||
// auto temp = clf->predict(Xtraint);
|
||||
// score_train = clf->score(Xtraint, ytraint);
|
||||
// score_test = clf->score(Xtestt, ytestt);
|
||||
// } else {
|
||||
// auto [Xtrain, ytrain] = extract_indices(train, Xd, y);
|
||||
// auto [Xtest, ytest] = extract_indices(test, Xd, y);
|
||||
// clf->fit(Xtrain, ytrain, features, className, states);
|
||||
// score_train = clf->score(Xtrain, ytrain);
|
||||
// score_test = clf->score(Xtest, ytest);
|
||||
// }
|
||||
// if (dump_cpt) {
|
||||
// cout << "--- CPT Tables ---" << endl;
|
||||
// clf->dump_cpt();
|
||||
// }
|
||||
// total_score_train += score_train;
|
||||
// total_score += score_test;
|
||||
// cout << "Score Train: " << score_train << endl;
|
||||
// cout << "Score Test : " << score_test << endl;
|
||||
// cout << "-------------------------------------------------------------------------------" << endl;
|
||||
// }
|
||||
// cout << "**********************************************************************************" << endl;
|
||||
// cout << "Average Score Train: " << total_score_train / nFolds << endl;
|
||||
// cout << "Average Score Test : " << total_score / nFolds << endl;return 0;
|
||||
}
|
34
src/BayesNet/AODELd.cc
Normal file
34
src/BayesNet/AODELd.cc
Normal file
@@ -0,0 +1,34 @@
|
||||
#include "AODELd.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
AODELd::AODELd() : Ensemble(), Proposal(Ensemble::Xv, Ensemble::yv, features, className) {}
|
||||
AODELd& AODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_)
|
||||
{
|
||||
features = features_;
|
||||
className = className_;
|
||||
states = states_;
|
||||
train();
|
||||
for (const auto& model : models) {
|
||||
model->fit(X_, y_, features_, className_, states_);
|
||||
}
|
||||
n_models = models.size();
|
||||
fitted = true;
|
||||
return *this;
|
||||
}
|
||||
void AODELd::train()
|
||||
{
|
||||
models.clear();
|
||||
for (int i = 0; i < features.size(); ++i) {
|
||||
models.push_back(std::make_unique<SPODELd>(i));
|
||||
}
|
||||
}
|
||||
Tensor AODELd::predict(Tensor& X)
|
||||
{
|
||||
return Ensemble::predict(X);
|
||||
}
|
||||
vector<string> AODELd::graph(const string& name)
|
||||
{
|
||||
return Ensemble::graph(name);
|
||||
}
|
||||
}
|
20
src/BayesNet/AODELd.h
Normal file
20
src/BayesNet/AODELd.h
Normal file
@@ -0,0 +1,20 @@
|
||||
#ifndef AODELD_H
|
||||
#define AODELD_H
|
||||
#include "Ensemble.h"
|
||||
#include "Proposal.h"
|
||||
#include "SPODELd.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
class AODELd : public Ensemble, public Proposal {
|
||||
public:
|
||||
AODELd();
|
||||
virtual ~AODELd() = default;
|
||||
AODELd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
vector<string> graph(const string& name = "AODE") override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
void train() override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
}
|
||||
#endif // !AODELD_H
|
@@ -10,6 +10,7 @@ namespace bayesnet {
|
||||
virtual BaseClassifier& fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states) = 0;
|
||||
// X is nxm tensor, y is nx1 tensor
|
||||
virtual BaseClassifier& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) = 0;
|
||||
virtual ~BaseClassifier() = default;
|
||||
torch::Tensor virtual predict(torch::Tensor& X) = 0;
|
||||
vector<int> virtual predict(vector<vector<int>>& X) = 0;
|
||||
float virtual score(vector<vector<int>>& X, vector<int>& y) = 0;
|
||||
@@ -19,7 +20,6 @@ namespace bayesnet {
|
||||
int virtual getNumberOfStates() = 0;
|
||||
vector<string> virtual show() = 0;
|
||||
vector<string> virtual graph(const string& title = "") = 0;
|
||||
virtual ~BaseClassifier() = default;
|
||||
const string inline getVersion() const { return "0.1.0"; };
|
||||
vector<string> virtual topological_order() = 0;
|
||||
void virtual dump_cpt() = 0;
|
||||
|
@@ -1,4 +1,5 @@
|
||||
include_directories(${BayesNet_SOURCE_DIR}/lib/mdlp)
|
||||
include_directories(${BayesNet_SOURCE_DIR}/lib/Files)
|
||||
add_library(BayesNet bayesnetUtils.cc Network.cc Node.cc BayesMetrics.cc Classifier.cc KDB.cc TAN.cc SPODE.cc Ensemble.cc AODE.cc TANNew.cc Mst.cc)
|
||||
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)
|
||||
target_link_libraries(BayesNet mdlp ArffFiles "${TORCH_LIBRARIES}")
|
@@ -1,6 +1,5 @@
|
||||
#include "Classifier.h"
|
||||
#include "bayesnetUtils.h"
|
||||
#include "ArffFiles.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace torch;
|
||||
@@ -37,15 +36,18 @@ namespace bayesnet {
|
||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
return build(features, className, states);
|
||||
}
|
||||
void Classifier::generateTensorXFromVector()
|
||||
{
|
||||
X = torch::zeros({ static_cast<int>(Xv.size()), static_cast<int>(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<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states)
|
||||
{
|
||||
|
||||
this->X = torch::zeros({ static_cast<int>(X.size()), static_cast<int>(X[0].size()) }, kInt32);
|
||||
Xv = X;
|
||||
for (int i = 0; i < X.size(); ++i) {
|
||||
this->X.index_put_({ i, "..." }, torch::tensor(X[i], kInt32));
|
||||
}
|
||||
generateTensorXFromVector();
|
||||
this->y = torch::tensor(y, kInt32);
|
||||
yv = y;
|
||||
return build(features, className, states);
|
||||
@@ -114,11 +116,9 @@ namespace bayesnet {
|
||||
{
|
||||
// Add all nodes to the network
|
||||
for (const auto& feature : features) {
|
||||
model.addNode(feature, states[feature].size());
|
||||
cout << "-Adding node " << feature << " with " << states[feature].size() << " states" << endl;
|
||||
model.addNode(feature);
|
||||
}
|
||||
model.addNode(className, states[className].size());
|
||||
cout << "*Adding class " << className << " with " << states[className].size() << " states" << endl;
|
||||
model.addNode(className);
|
||||
}
|
||||
int Classifier::getNumberOfNodes()
|
||||
{
|
||||
@@ -141,57 +141,5 @@ namespace bayesnet {
|
||||
{
|
||||
model.dump_cpt();
|
||||
}
|
||||
void Classifier::localDiscretizationProposal(map<string, mdlp::CPPFImdlp*>& discretizers, Tensor& Xf)
|
||||
{
|
||||
// order of local discretization is important. no good 0, 1, 2...
|
||||
auto order = model.topological_sort();
|
||||
auto& nodes = model.getNodes();
|
||||
vector<int> 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();
|
||||
int index = find(features.begin(), features.end(), feature) - features.begin();
|
||||
vector<string> parents;
|
||||
transform(nodeParents.begin(), nodeParents.end(), back_inserter(parents), [](const auto& p) {return p->getName(); });
|
||||
if (parents.size() == 1) continue; // Only has class as parent
|
||||
upgrade = true;
|
||||
// Remove class as parent as it will be added later
|
||||
parents.erase(remove(parents.begin(), parents.end(), className), parents.end());
|
||||
// Get the indices of the parents
|
||||
vector<int> indices;
|
||||
transform(parents.begin(), parents.end(), back_inserter(indices), [&](const auto& p) {return find(features.begin(), features.end(), p) - features.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<string> yJoinParents;
|
||||
transform(yv.begin(), yv.end(), back_inserter(yJoinParents), [&](const auto& p) {return to_string(p); });
|
||||
for (auto idx : indices) {
|
||||
for (int i = 0; i < n_samples; ++i) {
|
||||
yJoinParents[i] += to_string(Xv[idx][i]);
|
||||
}
|
||||
}
|
||||
auto arff = ArffFiles();
|
||||
auto yxv = arff.factorize(yJoinParents);
|
||||
auto xvf_ptr = Xf.index({ index }).data_ptr<float>();
|
||||
auto xvf = vector<mdlp::precision_t>(xvf_ptr, xvf_ptr + Xf.size(1));
|
||||
discretizers[feature]->fit(xvf, yxv);
|
||||
indicesToReDiscretize.push_back(index);
|
||||
}
|
||||
if (upgrade) {
|
||||
// Discretize again X (only the affected indices) with the new fitted discretizers
|
||||
for (auto index : indicesToReDiscretize) {
|
||||
auto Xt_ptr = Xf.index({ index }).data_ptr<float>();
|
||||
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
||||
Xv[index] = discretizers[features[index]]->transform(Xt);
|
||||
auto xStates = vector<int>(discretizers[features[index]]->getCutPoints().size() + 1);
|
||||
iota(xStates.begin(), xStates.end(), 0);
|
||||
states[features[index]] = xStates;
|
||||
}
|
||||
// Now we fit the model again with the new values
|
||||
cout << "Classifier: Upgrading model" << endl;
|
||||
// To update the nodes states
|
||||
addNodes();
|
||||
model.fit(Xv, yv, features, className);
|
||||
cout << "Classifier: Model upgraded" << endl;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -4,7 +4,6 @@
|
||||
#include "BaseClassifier.h"
|
||||
#include "Network.h"
|
||||
#include "BayesMetrics.h"
|
||||
#include "CPPFImdlp.h"
|
||||
using namespace std;
|
||||
using namespace torch;
|
||||
|
||||
@@ -26,8 +25,8 @@ namespace bayesnet {
|
||||
string className;
|
||||
map<string, vector<int>> states;
|
||||
void checkFitParameters();
|
||||
void generateTensorXFromVector();
|
||||
virtual void train() = 0;
|
||||
void localDiscretizationProposal(map<string, mdlp::CPPFImdlp*>& discretizers, Tensor& Xf);
|
||||
public:
|
||||
Classifier(Network model);
|
||||
virtual ~Classifier() = default;
|
||||
|
@@ -3,24 +3,24 @@
|
||||
namespace bayesnet {
|
||||
using namespace torch;
|
||||
|
||||
Ensemble::Ensemble() : m(0), n(0), n_models(0), metrics(Metrics()), fitted(false) {}
|
||||
Ensemble::Ensemble() : n_models(0), metrics(Metrics()), fitted(false) {}
|
||||
Ensemble& Ensemble::build(vector<string>& features, string className, map<string, vector<int>>& states)
|
||||
{
|
||||
dataset = cat({ X, y.view({y.size(0), 1}) }, 1);
|
||||
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(dataset, features, className, n_classes);
|
||||
metrics = Metrics(samples, features, className, n_classes);
|
||||
// Build models
|
||||
train();
|
||||
// Train models
|
||||
n_models = models.size();
|
||||
auto Xt = torch::transpose(X, 0, 1);
|
||||
for (auto i = 0; i < n_models; ++i) {
|
||||
if (Xv == vector<vector<int>>()) {
|
||||
if (Xv.empty()) {
|
||||
// fit with tensors
|
||||
models[i]->fit(Xt, y, features, className, states);
|
||||
models[i]->fit(X, y, features, className, states);
|
||||
} else {
|
||||
// fit with vectors
|
||||
models[i]->fit(Xv, yv, features, className, states);
|
||||
@@ -29,9 +29,16 @@ namespace bayesnet {
|
||||
fitted = true;
|
||||
return *this;
|
||||
}
|
||||
void Ensemble::generateTensorXFromVector()
|
||||
{
|
||||
X = torch::zeros({ static_cast<int>(Xv.size()), static_cast<int>(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<string>& features, string className, map<string, vector<int>>& states)
|
||||
{
|
||||
this->X = torch::transpose(X, 0, 1);
|
||||
this->X = X;
|
||||
this->y = y;
|
||||
Xv = vector<vector<int>>();
|
||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
@@ -39,11 +46,8 @@ namespace bayesnet {
|
||||
}
|
||||
Ensemble& Ensemble::fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states)
|
||||
{
|
||||
this->X = torch::zeros({ static_cast<int>(X[0].size()), static_cast<int>(X.size()) }, kInt32);
|
||||
Xv = X;
|
||||
for (int i = 0; i < X.size(); ++i) {
|
||||
this->X.index_put_({ "...", i }, torch::tensor(X[i], kInt32));
|
||||
}
|
||||
generateTensorXFromVector();
|
||||
this->y = torch::tensor(y, kInt32);
|
||||
yv = y;
|
||||
return build(features, className, states);
|
||||
@@ -53,10 +57,11 @@ namespace bayesnet {
|
||||
auto y_pred_ = y_pred.accessor<int, 2>();
|
||||
vector<int> y_pred_final;
|
||||
for (int i = 0; i < y_pred.size(0); ++i) {
|
||||
vector<float> votes(states[className].size(), 0);
|
||||
vector<float> votes(y_pred.size(1), 0);
|
||||
for (int j = 0; j < y_pred.size(1); ++j) {
|
||||
votes[y_pred_[i][j]] += 1;
|
||||
}
|
||||
// argsort in descending order
|
||||
auto indices = argsort(votes);
|
||||
y_pred_final.push_back(indices[0]);
|
||||
}
|
||||
@@ -70,13 +75,12 @@ namespace bayesnet {
|
||||
Tensor y_pred = torch::zeros({ X.size(1), n_models }, kInt32);
|
||||
//Create a threadpool
|
||||
auto threads{ vector<thread>() };
|
||||
auto lock = mutex();
|
||||
mutex mtx;
|
||||
for (auto i = 0; i < n_models; ++i) {
|
||||
threads.push_back(thread([&, i]() {
|
||||
auto ypredict = models[i]->predict(X);
|
||||
lock.lock();
|
||||
lock_guard<mutex> lock(mtx);
|
||||
y_pred.index_put_({ "...", i }, ypredict);
|
||||
lock.unlock();
|
||||
}));
|
||||
}
|
||||
for (auto& thread : threads) {
|
||||
|
@@ -10,23 +10,23 @@ using namespace torch;
|
||||
namespace bayesnet {
|
||||
class Ensemble : public BaseClassifier {
|
||||
private:
|
||||
bool fitted;
|
||||
long n_models;
|
||||
Ensemble& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
||||
protected:
|
||||
unsigned n_models;
|
||||
bool fitted;
|
||||
vector<unique_ptr<Classifier>> models;
|
||||
int m, n; // m: number of samples, n: number of features
|
||||
Tensor X;
|
||||
vector<vector<int>> Xv;
|
||||
Tensor y;
|
||||
vector<int> yv;
|
||||
Tensor dataset;
|
||||
Tensor samples;
|
||||
Metrics metrics;
|
||||
vector<string> features;
|
||||
string className;
|
||||
map<string, vector<int>> states;
|
||||
void virtual train() = 0;
|
||||
vector<int> voting(Tensor& y_pred);
|
||||
void generateTensorXFromVector();
|
||||
public:
|
||||
Ensemble();
|
||||
virtual ~Ensemble() = default;
|
||||
|
35
src/BayesNet/KDBLd.cc
Normal file
35
src/BayesNet/KDBLd.cc
Normal file
@@ -0,0 +1,35 @@
|
||||
#include "KDBLd.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
KDBLd::KDBLd(int k) : KDB(k), Proposal(KDB::Xv, KDB::yv, features, className) {}
|
||||
KDBLd& KDBLd::fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_)
|
||||
{
|
||||
// This first part should go in a Classifier method called fit_local_discretization o fit_float...
|
||||
features = features_;
|
||||
className = className_;
|
||||
Xf = X_;
|
||||
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);
|
||||
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)
|
||||
{
|
||||
auto Xt = prepareX(X);
|
||||
return KDB::predict(Xt);
|
||||
}
|
||||
vector<string> KDBLd::graph(const string& name)
|
||||
{
|
||||
return KDB::graph(name);
|
||||
}
|
||||
}
|
19
src/BayesNet/KDBLd.h
Normal file
19
src/BayesNet/KDBLd.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#ifndef KDBLD_H
|
||||
#define KDBLD_H
|
||||
#include "KDB.h"
|
||||
#include "Proposal.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
class KDBLd : public KDB, public Proposal {
|
||||
private:
|
||||
public:
|
||||
explicit KDBLd(int k);
|
||||
virtual ~KDBLd() = default;
|
||||
KDBLd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
vector<string> graph(const string& name = "KDB") override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
}
|
||||
#endif // !KDBLD_H
|
@@ -31,21 +31,18 @@ namespace bayesnet {
|
||||
{
|
||||
return samples;
|
||||
}
|
||||
void Network::addNode(const string& name, int numStates)
|
||||
void Network::addNode(const string& name)
|
||||
{
|
||||
if (name == "") {
|
||||
throw invalid_argument("Node name cannot be empty");
|
||||
}
|
||||
if (nodes.find(name) != nodes.end()) {
|
||||
return;
|
||||
}
|
||||
if (find(features.begin(), features.end(), name) == features.end()) {
|
||||
features.push_back(name);
|
||||
}
|
||||
if (nodes.find(name) != nodes.end()) {
|
||||
// if node exists update its number of states and remove parents, children and CPT
|
||||
nodes[name]->clear();
|
||||
nodes[name]->setNumStates(numStates);
|
||||
return;
|
||||
}
|
||||
nodes[name] = std::make_unique<Node>(name, numStates);
|
||||
nodes[name] = std::make_unique<Node>(name);
|
||||
}
|
||||
vector<string> Network::getFeatures()
|
||||
{
|
||||
@@ -128,14 +125,20 @@ namespace bayesnet {
|
||||
}
|
||||
}
|
||||
}
|
||||
void Network::setStates()
|
||||
{
|
||||
// Set states to every Node in the network
|
||||
for (int i = 0; i < features.size(); ++i) {
|
||||
nodes[features[i]]->setNumStates(static_cast<int>(torch::max(samples.index({ i, "..." })).item<int>()) + 1);
|
||||
}
|
||||
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<string>& featureNames, const string& className)
|
||||
{
|
||||
checkFitData(X.size(1), X.size(0), y.size(0), featureNames, className);
|
||||
this->className = className;
|
||||
dataset.clear();
|
||||
// Specific part
|
||||
classNumStates = torch::max(y).item<int>() + 1;
|
||||
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) {
|
||||
@@ -151,8 +154,6 @@ namespace bayesnet {
|
||||
checkFitData(input_data[0].size(), input_data.size(), labels.size(), featureNames, className);
|
||||
this->className = className;
|
||||
dataset.clear();
|
||||
// Specific part
|
||||
classNumStates = *max_element(labels.begin(), labels.end()) + 1;
|
||||
// Build dataset & tensor of samples (nxm) (n+1 because of the class)
|
||||
samples = torch::zeros({ static_cast<int>(input_data.size() + 1), static_cast<int>(input_data[0].size()) }, torch::kInt32);
|
||||
for (int i = 0; i < featureNames.size(); ++i) {
|
||||
@@ -165,6 +166,7 @@ namespace bayesnet {
|
||||
}
|
||||
void Network::completeFit()
|
||||
{
|
||||
setStates();
|
||||
int maxThreadsRunning = static_cast<int>(std::thread::hardware_concurrency() * maxThreads);
|
||||
if (maxThreadsRunning < 1) {
|
||||
maxThreadsRunning = 1;
|
||||
@@ -211,7 +213,10 @@ namespace bayesnet {
|
||||
result = torch::zeros({ samples.size(1), classNumStates }, torch::kFloat64);
|
||||
for (int i = 0; i < samples.size(1); ++i) {
|
||||
auto sample = samples.index({ "...", i });
|
||||
result.index_put_({ i, "..." }, torch::tensor(predict_sample(sample), torch::kFloat64));
|
||||
auto psample = predict_sample(sample);
|
||||
auto temp = torch::tensor(psample, torch::kFloat64);
|
||||
// result.index_put_({ i, "..." }, torch::tensor(predict_sample(sample), torch::kFloat64));
|
||||
result.index_put_({ i, "..." }, temp);
|
||||
}
|
||||
if (proba)
|
||||
return result;
|
||||
@@ -323,17 +328,16 @@ namespace bayesnet {
|
||||
mutex mtx;
|
||||
for (int i = 0; i < classNumStates; ++i) {
|
||||
threads.emplace_back([this, &result, &evidence, i, &mtx]() {
|
||||
auto completeEvidence = map<string, int>(evidence);
|
||||
completeEvidence[getClassName()] = i;
|
||||
auto completeEvidence = map<string, int>(evidence);
|
||||
completeEvidence[getClassName()] = i;
|
||||
double factor = computeFactor(completeEvidence);
|
||||
lock_guard<mutex> lock(mtx);
|
||||
result[i] = factor;
|
||||
});
|
||||
});
|
||||
}
|
||||
for (auto& thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
|
||||
// Normalize result
|
||||
double sum = accumulate(result.begin(), result.end(), 0.0);
|
||||
transform(result.begin(), result.end(), result.begin(), [sum](double& value) { return value / sum; });
|
||||
@@ -419,7 +423,7 @@ namespace bayesnet {
|
||||
void Network::dump_cpt()
|
||||
{
|
||||
for (auto& node : nodes) {
|
||||
cout << "* " << node.first << ": " << node.second->getCPT() << endl;
|
||||
cout << "* " << node.first << ": (" << node.second->getNumStates() << ") : " << node.second->getCPT().sizes() << endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -27,6 +27,7 @@ namespace bayesnet {
|
||||
double mutualInformation(torch::Tensor&, torch::Tensor&);
|
||||
void completeFit();
|
||||
void checkFitData(int n_features, int n_samples, int n_samples_y, const vector<string>& featureNames, const string& className);
|
||||
void setStates();
|
||||
public:
|
||||
Network();
|
||||
explicit Network(float, int);
|
||||
@@ -34,7 +35,7 @@ namespace bayesnet {
|
||||
explicit Network(Network&);
|
||||
torch::Tensor& getSamples();
|
||||
float getmaxThreads();
|
||||
void addNode(const string&, int);
|
||||
void addNode(const string&);
|
||||
void addEdge(const string&, const string&);
|
||||
map<string, std::unique_ptr<Node>>& getNodes();
|
||||
vector<string> getFeatures();
|
||||
|
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace bayesnet {
|
||||
|
||||
Node::Node(const std::string& name, int numStates)
|
||||
: name(name), numStates(numStates), cpTable(torch::Tensor()), parents(vector<Node*>()), children(vector<Node*>())
|
||||
Node::Node(const std::string& name)
|
||||
: name(name), numStates(0), cpTable(torch::Tensor()), parents(vector<Node*>()), children(vector<Node*>())
|
||||
{
|
||||
}
|
||||
void Node::clear()
|
||||
@@ -86,6 +86,7 @@ namespace bayesnet {
|
||||
}
|
||||
void Node::computeCPT(map<string, vector<int>>& dataset, const int laplaceSmoothing)
|
||||
{
|
||||
dimensions.clear();
|
||||
// Get dimensions of the CPT
|
||||
dimensions.push_back(numStates);
|
||||
transform(parents.begin(), parents.end(), back_inserter(dimensions), [](const auto& parent) { return parent->getNumStates(); });
|
||||
|
@@ -16,7 +16,7 @@ namespace bayesnet {
|
||||
vector<int64_t> dimensions; // dimensions of the cpTable
|
||||
public:
|
||||
vector<pair<string, string>> combinations(const vector<string>&);
|
||||
Node(const string&, int);
|
||||
explicit Node(const string&);
|
||||
void clear();
|
||||
void addParent(Node*);
|
||||
void addChild(Node*);
|
||||
|
102
src/BayesNet/Proposal.cc
Normal file
102
src/BayesNet/Proposal.cc
Normal file
@@ -0,0 +1,102 @@
|
||||
#include "Proposal.h"
|
||||
#include "ArffFiles.h"
|
||||
|
||||
namespace bayesnet {
|
||||
Proposal::Proposal(vector<vector<int>>& Xv_, vector<int>& yv_, vector<string>& features_, string& className_) : Xv(Xv_), yv(yv_), pFeatures(features_), pClassName(className_) {}
|
||||
Proposal::~Proposal()
|
||||
{
|
||||
for (auto& [key, value] : discretizers) {
|
||||
delete value;
|
||||
}
|
||||
}
|
||||
void Proposal::localDiscretizationProposal(map<string, vector<int>>& states, Network& model)
|
||||
{
|
||||
// order of local discretization is important. no good 0, 1, 2...
|
||||
// although we rediscretize features after the local discretization of every feature
|
||||
auto order = model.topological_sort();
|
||||
auto& nodes = model.getNodes();
|
||||
vector<int> 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();
|
||||
if (nodeParents.size() < 2) continue; // Only has class as parent
|
||||
upgrade = true;
|
||||
int index = find(pFeatures.begin(), pFeatures.end(), feature) - pFeatures.begin();
|
||||
indicesToReDiscretize.push_back(index); // We need to re-discretize this feature
|
||||
vector<string> parents;
|
||||
transform(nodeParents.begin(), nodeParents.end(), back_inserter(parents), [](const auto& p) { return p->getName(); });
|
||||
// Remove class as parent as it will be added later
|
||||
parents.erase(remove(parents.begin(), parents.end(), pClassName), parents.end());
|
||||
// Get the indices of the parents
|
||||
vector<int> indices;
|
||||
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<string> yJoinParents;
|
||||
transform(yv.begin(), yv.end(), back_inserter(yJoinParents), [&](const auto& p) {return to_string(p); });
|
||||
for (auto idx : indices) {
|
||||
for (int i = 0; i < n_samples; ++i) {
|
||||
yJoinParents[i] += to_string(Xv[idx][i]);
|
||||
}
|
||||
}
|
||||
auto arff = ArffFiles();
|
||||
auto yxv = arff.factorize(yJoinParents);
|
||||
auto xvf_ptr = Xf.index({ index }).data_ptr<float>();
|
||||
auto xvf = vector<mdlp::precision_t>(xvf_ptr, xvf_ptr + Xf.size(1));
|
||||
discretizers[feature]->fit(xvf, yxv);
|
||||
//
|
||||
//
|
||||
//
|
||||
// auto tmp = discretizers[feature]->transform(xvf);
|
||||
// Xv[index] = tmp;
|
||||
// auto xStates = vector<int>(discretizers[pFeatures[index]]->getCutPoints().size() + 1);
|
||||
// iota(xStates.begin(), xStates.end(), 0);
|
||||
// //Update new states of the feature/node
|
||||
// states[feature] = xStates;
|
||||
}
|
||||
if (upgrade) {
|
||||
// Discretize again X (only the affected indices) with the new fitted discretizers
|
||||
for (auto index : indicesToReDiscretize) {
|
||||
auto Xt_ptr = Xf.index({ index }).data_ptr<float>();
|
||||
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
||||
Xv[index] = discretizers[pFeatures[index]]->transform(Xt);
|
||||
auto xStates = vector<int>(discretizers[pFeatures[index]]->getCutPoints().size() + 1);
|
||||
iota(xStates.begin(), xStates.end(), 0);
|
||||
//Update new states of the feature/node
|
||||
states[pFeatures[index]] = xStates;
|
||||
}
|
||||
}
|
||||
}
|
||||
void Proposal::fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y)
|
||||
{
|
||||
// Sharing Xv and yv with Classifier
|
||||
Xv = vector<vector<int>>();
|
||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
// discretize input data by feature(row)
|
||||
for (int i = 0; i < pFeatures.size(); ++i) {
|
||||
auto* discretizer = new mdlp::CPPFImdlp();
|
||||
auto Xt_ptr = Xf.index({ i }).data_ptr<float>();
|
||||
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
||||
discretizer->fit(Xt, yv);
|
||||
Xv.push_back(discretizer->transform(Xt));
|
||||
auto xStates = vector<int>(discretizer->getCutPoints().size() + 1);
|
||||
iota(xStates.begin(), xStates.end(), 0);
|
||||
states[pFeatures[i]] = xStates;
|
||||
discretizers[pFeatures[i]] = discretizer;
|
||||
}
|
||||
int n_classes = torch::max(y).item<int>() + 1;
|
||||
auto yStates = vector<int>(n_classes);
|
||||
iota(yStates.begin(), yStates.end(), 0);
|
||||
states[pClassName] = yStates;
|
||||
}
|
||||
torch::Tensor Proposal::prepareX(torch::Tensor& X)
|
||||
{
|
||||
auto Xtd = torch::zeros_like(X, torch::kInt32);
|
||||
for (int i = 0; i < X.size(0); ++i) {
|
||||
auto Xt = vector<float>(X[i].data_ptr<float>(), X[i].data_ptr<float>() + X.size(1));
|
||||
auto Xd = discretizers[pFeatures[i]]->transform(Xt);
|
||||
Xtd.index_put_({ i }, torch::tensor(Xd, torch::kInt32));
|
||||
}
|
||||
return Xtd;
|
||||
}
|
||||
}
|
29
src/BayesNet/Proposal.h
Normal file
29
src/BayesNet/Proposal.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef PROPOSAL_H
|
||||
#define PROPOSAL_H
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <torch/torch.h>
|
||||
#include "Network.h"
|
||||
#include "CPPFImdlp.h"
|
||||
#include "Classifier.h"
|
||||
|
||||
namespace bayesnet {
|
||||
class Proposal {
|
||||
public:
|
||||
Proposal(vector<vector<int>>& Xv_, vector<int>& yv_, vector<string>& features_, string& className_);
|
||||
virtual ~Proposal();
|
||||
protected:
|
||||
torch::Tensor prepareX(torch::Tensor& X);
|
||||
void localDiscretizationProposal(map<string, vector<int>>& states, Network& model);
|
||||
void fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y);
|
||||
torch::Tensor Xf; // X continuous nxm tensor
|
||||
map<string, mdlp::CPPFImdlp*> discretizers;
|
||||
private:
|
||||
vector<string>& pFeatures;
|
||||
string& pClassName;
|
||||
vector<vector<int>>& Xv; // X discrete nxm vector
|
||||
vector<int>& yv;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
35
src/BayesNet/SPODELd.cc
Normal file
35
src/BayesNet/SPODELd.cc
Normal file
@@ -0,0 +1,35 @@
|
||||
#include "SPODELd.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
SPODELd::SPODELd(int root) : SPODE(root), Proposal(SPODE::Xv, SPODE::yv, features, className) {}
|
||||
SPODELd& SPODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_)
|
||||
{
|
||||
// This first part should go in a Classifier method called fit_local_discretization o fit_float...
|
||||
features = features_;
|
||||
className = className_;
|
||||
Xf = X_;
|
||||
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);
|
||||
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);
|
||||
return *this;
|
||||
}
|
||||
Tensor SPODELd::predict(Tensor& X)
|
||||
{
|
||||
auto Xt = prepareX(X);
|
||||
return SPODE::predict(Xt);
|
||||
}
|
||||
vector<string> SPODELd::graph(const string& name)
|
||||
{
|
||||
return SPODE::graph(name);
|
||||
}
|
||||
}
|
19
src/BayesNet/SPODELd.h
Normal file
19
src/BayesNet/SPODELd.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#ifndef SPODELD_H
|
||||
#define SPODELD_H
|
||||
#include "SPODE.h"
|
||||
#include "Proposal.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
class SPODELd : public SPODE, public Proposal {
|
||||
private:
|
||||
public:
|
||||
explicit SPODELd(int root);
|
||||
virtual ~SPODELd() = default;
|
||||
SPODELd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
vector<string> graph(const string& name = "SPODE") override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
}
|
||||
#endif // !SPODELD_H
|
35
src/BayesNet/TANLd.cc
Normal file
35
src/BayesNet/TANLd.cc
Normal file
@@ -0,0 +1,35 @@
|
||||
#include "TANLd.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
TANLd::TANLd() : TAN(), Proposal(TAN::Xv, TAN::yv, features, className) {}
|
||||
TANLd& TANLd::fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_)
|
||||
{
|
||||
// This first part should go in a Classifier method called fit_local_discretization o fit_float...
|
||||
features = features_;
|
||||
className = className_;
|
||||
Xf = X_;
|
||||
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);
|
||||
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);
|
||||
return *this;
|
||||
}
|
||||
Tensor TANLd::predict(Tensor& X)
|
||||
{
|
||||
auto Xt = prepareX(X);
|
||||
return TAN::predict(Xt);
|
||||
}
|
||||
vector<string> TANLd::graph(const string& name)
|
||||
{
|
||||
return TAN::graph(name);
|
||||
}
|
||||
}
|
19
src/BayesNet/TANLd.h
Normal file
19
src/BayesNet/TANLd.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#ifndef TANLD_H
|
||||
#define TANLD_H
|
||||
#include "TAN.h"
|
||||
#include "Proposal.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
class TANLd : public TAN, public Proposal {
|
||||
private:
|
||||
public:
|
||||
TANLd();
|
||||
virtual ~TANLd() = default;
|
||||
TANLd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
vector<string> graph(const string& name = "TAN") override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
}
|
||||
#endif // !TANLD_H
|
@@ -1,55 +0,0 @@
|
||||
#include "TANNew.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
TANNew::TANNew() : TAN() {}
|
||||
TANNew::~TANNew() {}
|
||||
TANNew& TANNew::fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_)
|
||||
{
|
||||
Xf = X_;
|
||||
y = y_;
|
||||
features = features_;
|
||||
className = className_;
|
||||
Xv = vector<vector<int>>();
|
||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
// discretize input data by feature(row)
|
||||
for (int i = 0; i < features.size(); ++i) {
|
||||
auto* discretizer = new mdlp::CPPFImdlp();
|
||||
auto Xt_ptr = Xf.index({ i }).data_ptr<float>();
|
||||
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
||||
discretizer->fit(Xt, yv);
|
||||
Xv.push_back(discretizer->transform(Xt));
|
||||
auto xStates = vector<int>(discretizer->getCutPoints().size() + 1);
|
||||
iota(xStates.begin(), xStates.end(), 0);
|
||||
states[features[i]] = xStates;
|
||||
discretizers[features[i]] = discretizer;
|
||||
}
|
||||
int n_classes = torch::max(y).item<int>() + 1;
|
||||
auto yStates = vector<int>(n_classes);
|
||||
iota(yStates.begin(), yStates.end(), 0);
|
||||
states[className] = yStates;
|
||||
// Now we have standard TAN and now we implement the proposal
|
||||
// 1st we need to fit the model to build the TAN structure
|
||||
cout << "TANNew: Fitting model" << endl;
|
||||
TAN::fit(Xv, yv, features, className, states);
|
||||
cout << "TANNew: Model fitted" << endl;
|
||||
localDiscretizationProposal(discretizers, Xf);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Tensor TANNew::predict(Tensor& X)
|
||||
{
|
||||
auto Xtd = torch::zeros_like(X, torch::kInt32);
|
||||
for (int i = 0; i < X.size(0); ++i) {
|
||||
auto Xt = vector<float>(X[i].data_ptr<float>(), X[i].data_ptr<float>() + X.size(1));
|
||||
auto Xd = discretizers[features[i]]->transform(Xt);
|
||||
Xtd.index_put_({ i }, torch::tensor(Xd, torch::kInt32));
|
||||
}
|
||||
cout << "TANNew Xtd: " << Xtd.sizes() << endl;
|
||||
return TAN::predict(Xtd);
|
||||
}
|
||||
vector<string> TANNew::graph(const string& name)
|
||||
{
|
||||
return TAN::graph(name);
|
||||
}
|
||||
}
|
@@ -1,21 +0,0 @@
|
||||
#ifndef TANNEW_H
|
||||
#define TANNEW_H
|
||||
#include "TAN.h"
|
||||
#include "CPPFImdlp.h"
|
||||
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
class TANNew : public TAN {
|
||||
private:
|
||||
map<string, mdlp::CPPFImdlp*> discretizers;
|
||||
torch::Tensor Xf; // X continuous nxm tensor
|
||||
public:
|
||||
TANNew();
|
||||
virtual ~TANNew();
|
||||
TANNew& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
vector<string> graph(const string& name = "TAN") override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
}
|
||||
#endif // !TANNEW_H
|
@@ -3,6 +3,7 @@
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
using namespace torch;
|
||||
// Return the indices in descending order
|
||||
vector<int> argsort(vector<float>& nums)
|
||||
{
|
||||
int n = nums.size();
|
||||
|
@@ -4,5 +4,5 @@ include_directories(${BayesNet_SOURCE_DIR}/lib/Files)
|
||||
include_directories(${BayesNet_SOURCE_DIR}/lib/mdlp)
|
||||
include_directories(${BayesNet_SOURCE_DIR}/lib/argparse/include)
|
||||
include_directories(${BayesNet_SOURCE_DIR}/lib/json/include)
|
||||
add_executable(main main.cc Folding.cc platformUtils.cc Experiment.cc Datasets.cc Models.cc)
|
||||
add_executable(main main.cc Folding.cc platformUtils.cc Experiment.cc Datasets.cc Models.cc Report.cc)
|
||||
target_link_libraries(main BayesNet ArffFiles mdlp "${TORCH_LIBRARIES}")
|
@@ -1,6 +1,7 @@
|
||||
#include "Experiment.h"
|
||||
#include "Datasets.h"
|
||||
#include "Models.h"
|
||||
#include "Report.h"
|
||||
|
||||
namespace platform {
|
||||
using json = nlohmann::json;
|
||||
@@ -86,6 +87,13 @@ namespace platform {
|
||||
file.close();
|
||||
}
|
||||
|
||||
void Experiment::report()
|
||||
{
|
||||
json data = build_json();
|
||||
Report report(data);
|
||||
report.show();
|
||||
}
|
||||
|
||||
void Experiment::show()
|
||||
{
|
||||
json data = build_json();
|
||||
|
@@ -108,6 +108,7 @@ namespace platform {
|
||||
void cross_validation(const string& path, const string& fileName);
|
||||
void go(vector<string> filesToProcess, const string& path);
|
||||
void show();
|
||||
void report();
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -6,7 +6,10 @@
|
||||
#include "TAN.h"
|
||||
#include "KDB.h"
|
||||
#include "SPODE.h"
|
||||
#include "TANNew.h"
|
||||
#include "TANLd.h"
|
||||
#include "KDBLd.h"
|
||||
#include "SPODELd.h"
|
||||
#include "AODELd.h"
|
||||
namespace platform {
|
||||
class Models {
|
||||
private:
|
||||
|
66
src/Platform/Report.cc
Normal file
66
src/Platform/Report.cc
Normal file
@@ -0,0 +1,66 @@
|
||||
#include "Report.h"
|
||||
|
||||
namespace platform {
|
||||
string headerLine(const string& text)
|
||||
{
|
||||
int n = MAXL - text.length() - 3;
|
||||
return "* " + text + string(n, ' ') + "*\n";
|
||||
}
|
||||
string Report::fromVector(const string& key)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
for (auto& item : data[key]) {
|
||||
result += to_string(item) + ", ";
|
||||
}
|
||||
return "[" + result.substr(0, result.length() - 2) + "]";
|
||||
}
|
||||
string fVector(const json& data)
|
||||
{
|
||||
string result = "";
|
||||
for (const auto& item : data) {
|
||||
result += to_string(item) + ", ";
|
||||
}
|
||||
return "[" + result.substr(0, result.length() - 2) + "]";
|
||||
}
|
||||
void Report::show()
|
||||
{
|
||||
header();
|
||||
body();
|
||||
}
|
||||
void Report::header()
|
||||
{
|
||||
cout << string(MAXL, '*') << endl;
|
||||
cout << headerLine("Report " + data["model"].get<string>() + " ver. " + data["version"].get<string>() + " with " + to_string(data["folds"].get<int>()) + " Folds cross validation and " + to_string(data["seeds"].size()) + " random seeds. " + data["date"].get<string>() + " " + data["time"].get<string>());
|
||||
cout << headerLine(data["title"].get<string>());
|
||||
cout << headerLine("Random seeds: " + fromVector("seeds") + " Stratified: " + (data["stratified"].get<bool>() ? "True" : "False"));
|
||||
cout << headerLine("Execution took " + to_string(data["duration"].get<float>()) + " seconds, " + to_string(data["duration"].get<float>() / 3600) + " hours, on " + data["platform"].get<string>());
|
||||
cout << headerLine("Score is " + data["score_name"].get<string>());
|
||||
cout << string(MAXL, '*') << endl;
|
||||
cout << endl;
|
||||
}
|
||||
void Report::body()
|
||||
{
|
||||
cout << "Dataset Sampl. Feat. Cls Nodes Edges States Score Time Hyperparameters" << endl;
|
||||
cout << "============================== ====== ===== === ======= ======= ======= =============== ================= ===============" << endl;
|
||||
for (const auto& r : data["results"]) {
|
||||
cout << setw(30) << left << r["dataset"].get<string>() << " ";
|
||||
cout << setw(6) << right << r["samples"].get<int>() << " ";
|
||||
cout << setw(5) << right << r["features"].get<int>() << " ";
|
||||
cout << setw(3) << right << r["classes"].get<int>() << " ";
|
||||
cout << setw(7) << setprecision(2) << fixed << r["nodes"].get<float>() << " ";
|
||||
cout << setw(7) << setprecision(2) << fixed << r["leaves"].get<float>() << " ";
|
||||
cout << setw(7) << setprecision(2) << fixed << r["depth"].get<float>() << " ";
|
||||
cout << setw(8) << right << setprecision(6) << fixed << r["score_test"].get<double>() << "±" << setw(6) << setprecision(4) << fixed << r["score_test_std"].get<double>() << " ";
|
||||
cout << setw(10) << right << setprecision(6) << fixed << r["test_time"].get<double>() << "±" << setw(6) << setprecision(4) << fixed << r["test_time_std"].get<double>() << " ";
|
||||
cout << " " << r["hyperparameters"].get<string>();
|
||||
cout << endl;
|
||||
cout << string(MAXL, '*') << endl;
|
||||
cout << headerLine("Train scores: " + fVector(r["scores_train"]));
|
||||
cout << headerLine("Test scores: " + fVector(r["scores_test"]));
|
||||
cout << headerLine("Train times: " + fVector(r["times_train"]));
|
||||
cout << headerLine("Test times: " + fVector(r["times_test"]));
|
||||
cout << string(MAXL, '*') << endl;
|
||||
}
|
||||
}
|
||||
}
|
23
src/Platform/Report.h
Normal file
23
src/Platform/Report.h
Normal file
@@ -0,0 +1,23 @@
|
||||
#ifndef REPORT_H
|
||||
#define REPORT_H
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
const int MAXL = 121;
|
||||
namespace platform {
|
||||
using namespace std;
|
||||
class Report {
|
||||
public:
|
||||
explicit Report(json data_) { data = data_; };
|
||||
virtual ~Report() = default;
|
||||
void show();
|
||||
private:
|
||||
void header();
|
||||
void body();
|
||||
string fromVector(const string& key);
|
||||
json data;
|
||||
};
|
||||
};
|
||||
#endif
|
@@ -102,9 +102,10 @@ int main(int argc, char** argv)
|
||||
/*
|
||||
* Begin Processing
|
||||
*/
|
||||
auto env = platform::DotEnv();
|
||||
auto experiment = platform::Experiment();
|
||||
experiment.setTitle(title).setLanguage("cpp").setLanguageVersion("1.0.0");
|
||||
experiment.setDiscretized(discretize_dataset).setModel(model_name).setPlatform("BayesNet");
|
||||
experiment.setDiscretized(discretize_dataset).setModel(model_name).setPlatform(env.get("platform"));
|
||||
experiment.setStratified(stratified).setNFolds(n_folds).setScoreName("accuracy");
|
||||
for (auto seed : seeds) {
|
||||
experiment.addRandomSeed(seed);
|
||||
@@ -116,7 +117,7 @@ int main(int argc, char** argv)
|
||||
if (saveResults)
|
||||
experiment.save(PATH_RESULTS);
|
||||
else
|
||||
experiment.show();
|
||||
experiment.report();
|
||||
cout << "Done!" << endl;
|
||||
return 0;
|
||||
}
|
||||
|
@@ -2,12 +2,18 @@
|
||||
#define MODEL_REGISTER_H
|
||||
static platform::Registrar registrarT("TAN",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::TAN();});
|
||||
static platform::Registrar registrarTN("TANNew",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::TANNew();});
|
||||
static platform::Registrar registrarTLD("TANLd",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::TANLd();});
|
||||
static platform::Registrar registrarS("SPODE",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::SPODE(2);});
|
||||
static platform::Registrar registrarSLD("SPODELd",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::SPODELd(2);});
|
||||
static platform::Registrar registrarK("KDB",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::KDB(2);});
|
||||
static platform::Registrar registrarKLD("KDBLd",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::KDBLd(2);});
|
||||
static platform::Registrar registrarA("AODE",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::AODE();});
|
||||
static platform::Registrar registrarALD("AODELd",
|
||||
[](void) -> bayesnet::BaseClassifier* { return new bayesnet::AODELd();});
|
||||
#endif
|
@@ -9,29 +9,21 @@ TEST_CASE("Test Bayesian Network")
|
||||
{
|
||||
auto [Xd, y, features, className, states] = loadFile("iris");
|
||||
|
||||
SECTION("Test Update Nodes")
|
||||
{
|
||||
auto net = bayesnet::Network();
|
||||
net.addNode("A", 3);
|
||||
REQUIRE(net.getStates() == 3);
|
||||
net.addNode("A", 5);
|
||||
REQUIRE(net.getStates() == 5);
|
||||
}
|
||||
SECTION("Test get features")
|
||||
{
|
||||
auto net = bayesnet::Network();
|
||||
net.addNode("A", 3);
|
||||
net.addNode("B", 5);
|
||||
net.addNode("A");
|
||||
net.addNode("B");
|
||||
REQUIRE(net.getFeatures() == vector<string>{"A", "B"});
|
||||
net.addNode("C", 2);
|
||||
net.addNode("C");
|
||||
REQUIRE(net.getFeatures() == vector<string>{"A", "B", "C"});
|
||||
}
|
||||
SECTION("Test get edges")
|
||||
{
|
||||
auto net = bayesnet::Network();
|
||||
net.addNode("A", 3);
|
||||
net.addNode("B", 5);
|
||||
net.addNode("C", 2);
|
||||
net.addNode("A");
|
||||
net.addNode("B");
|
||||
net.addNode("C");
|
||||
net.addEdge("A", "B");
|
||||
net.addEdge("B", "C");
|
||||
REQUIRE(net.getEdges() == vector<pair<string, string>>{ {"A", "B"}, { "B", "C" } });
|
||||
|
Reference in New Issue
Block a user