Compare commits
15 Commits
Author | SHA1 | Date | |
---|---|---|---|
2a3fc9aa45
|
|||
55d21294d5
|
|||
3691cb4a61
|
|||
054567c65a
|
|||
2729b92f06
|
|||
90c92e5c56 | |||
182b52a887
|
|||
6679b90a82 | |||
405887f833
|
|||
3a85481a5a
|
|||
0ad5505c16
|
|||
323444b74a
|
|||
ef1bffcac3
|
|||
06db8f51ce
|
|||
e74565ba01
|
@@ -13,5 +13,4 @@ HeaderFilterRegex: 'src/*'
|
||||
AnalyzeTemporaryDtors: false
|
||||
WarningsAsErrors: ''
|
||||
FormatStyle: file
|
||||
FormatStyleOptions: ''
|
||||
...
|
||||
|
13
.vscode/launch.json
vendored
13
.vscode/launch.json
vendored
@@ -25,7 +25,7 @@
|
||||
"program": "${workspaceFolder}/build/src/Platform/main",
|
||||
"args": [
|
||||
"-m",
|
||||
"AODELd",
|
||||
"SPODELd",
|
||||
"-p",
|
||||
"/Users/rmontanana/Code/discretizbench/datasets",
|
||||
"--stratified",
|
||||
@@ -34,6 +34,17 @@
|
||||
],
|
||||
"cwd": "/Users/rmontanana/Code/discretizbench",
|
||||
},
|
||||
{
|
||||
"type": "lldb",
|
||||
"request": "launch",
|
||||
"name": "manage",
|
||||
"program": "${workspaceFolder}/build/src/Platform/manage",
|
||||
"args": [
|
||||
"-n",
|
||||
"20"
|
||||
],
|
||||
"cwd": "/Users/rmontanana/Code/discretizbench",
|
||||
},
|
||||
{
|
||||
"name": "Build & debug active file",
|
||||
"type": "cppdbg",
|
||||
|
@@ -2,14 +2,14 @@
|
||||
|
||||
namespace bayesnet {
|
||||
AODE::AODE() : Ensemble() {}
|
||||
void AODE::train()
|
||||
void AODE::buildModel()
|
||||
{
|
||||
models.clear();
|
||||
for (int i = 0; i < features.size(); ++i) {
|
||||
models.push_back(std::make_unique<SPODE>(i));
|
||||
}
|
||||
}
|
||||
vector<string> AODE::graph(const string& title)
|
||||
vector<string> AODE::graph(const string& title) const
|
||||
{
|
||||
return Ensemble::graph(title);
|
||||
}
|
||||
|
@@ -5,11 +5,11 @@
|
||||
namespace bayesnet {
|
||||
class AODE : public Ensemble {
|
||||
protected:
|
||||
void train() override;
|
||||
void buildModel() override;
|
||||
public:
|
||||
AODE();
|
||||
virtual ~AODE() {};
|
||||
vector<string> graph(const string& title = "AODE") override;
|
||||
vector<string> graph(const string& title = "AODE") const override;
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -1,33 +1,39 @@
|
||||
#include "AODELd.h"
|
||||
#include "Models.h"
|
||||
|
||||
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<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_;
|
||||
states = states_;
|
||||
train();
|
||||
for (const auto& model : models) {
|
||||
model->fit(X_, y_, features_, className_, states_);
|
||||
}
|
||||
n_models = models.size();
|
||||
fitted = true;
|
||||
Xf = X_;
|
||||
y = y_;
|
||||
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & 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);
|
||||
return *this;
|
||||
|
||||
}
|
||||
void AODELd::train()
|
||||
void AODELd::buildModel()
|
||||
{
|
||||
models.clear();
|
||||
for (int i = 0; i < features.size(); ++i) {
|
||||
models.push_back(std::make_unique<SPODELd>(i));
|
||||
}
|
||||
n_models = models.size();
|
||||
}
|
||||
Tensor AODELd::predict(Tensor& X)
|
||||
void AODELd::trainModel()
|
||||
{
|
||||
return Ensemble::predict(X);
|
||||
for (const auto& model : models) {
|
||||
model->fit(Xf, y, features, className, states);
|
||||
}
|
||||
}
|
||||
vector<string> AODELd::graph(const string& name)
|
||||
vector<string> AODELd::graph(const string& name) const
|
||||
{
|
||||
return Ensemble::graph(name);
|
||||
}
|
||||
|
@@ -7,13 +7,14 @@
|
||||
namespace bayesnet {
|
||||
using namespace std;
|
||||
class AODELd : public Ensemble, public Proposal {
|
||||
protected:
|
||||
void trainModel() override;
|
||||
void buildModel() override;
|
||||
public:
|
||||
AODELd();
|
||||
AODELd& fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_) override;
|
||||
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;
|
||||
vector<string> graph(const string& name = "AODE") const override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
}
|
||||
|
@@ -5,24 +5,27 @@
|
||||
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<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& fit(torch::Tensor& dataset, 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;
|
||||
float virtual score(torch::Tensor& X, torch::Tensor& y) = 0;
|
||||
int virtual getNumberOfNodes() = 0;
|
||||
int virtual getNumberOfEdges() = 0;
|
||||
int virtual getNumberOfStates() = 0;
|
||||
vector<string> virtual show() = 0;
|
||||
vector<string> virtual graph(const string& title = "") = 0;
|
||||
int virtual getNumberOfNodes()const = 0;
|
||||
int virtual getNumberOfEdges()const = 0;
|
||||
int virtual getNumberOfStates() const = 0;
|
||||
vector<string> virtual show() const = 0;
|
||||
vector<string> virtual graph(const string& title = "") const = 0;
|
||||
const string inline getVersion() const { return "0.1.0"; };
|
||||
vector<string> virtual topological_order() = 0;
|
||||
void virtual dump_cpt() = 0;
|
||||
void virtual dump_cpt()const = 0;
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -2,7 +2,7 @@
|
||||
#include "Mst.h"
|
||||
namespace bayesnet {
|
||||
//samples is nxm tensor used to fit the model
|
||||
Metrics::Metrics(torch::Tensor& samples, vector<string>& features, string& className, int classNumStates)
|
||||
Metrics::Metrics(const torch::Tensor& samples, const vector<string>& features, const string& className, const int classNumStates)
|
||||
: samples(samples)
|
||||
, features(features)
|
||||
, className(className)
|
||||
@@ -76,7 +76,7 @@ namespace bayesnet {
|
||||
std::vector<float> v(matrix.data_ptr<float>(), matrix.data_ptr<float>() + 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<int>();
|
||||
@@ -86,7 +86,7 @@ namespace bayesnet {
|
||||
return entropy.nansum().item<double>();
|
||||
}
|
||||
// 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<pair<int, int>> Metrics::maximumSpanningTree(vector<string> features, Tensor& weights, int root)
|
||||
vector<pair<int, int>> Metrics::maximumSpanningTree(const vector<string>& features, const Tensor& weights, const int root)
|
||||
{
|
||||
auto mst = MST(features, weights, root);
|
||||
return mst.maximumSpanningTree();
|
||||
|
@@ -14,15 +14,15 @@ namespace bayesnet {
|
||||
int classNumStates = 0;
|
||||
public:
|
||||
Metrics() = default;
|
||||
Metrics(Tensor&, vector<string>&, string&, int);
|
||||
Metrics(const Tensor&, const vector<string>&, const string&, const int);
|
||||
Metrics(const vector<vector<int>>&, const vector<int>&, const vector<string>&, 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<float> conditionalEdgeWeights(); // To use in Python
|
||||
Tensor conditionalEdge();
|
||||
vector<pair<string, string>> doCombinations(const vector<string>&);
|
||||
vector<pair<int, int>> maximumSpanningTree(vector<string> features, Tensor& weights, int root);
|
||||
vector<pair<int, int>> maximumSpanningTree(const vector<string>& features, const Tensor& weights, const int root);
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -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}")
|
@@ -7,61 +7,65 @@ namespace bayesnet {
|
||||
Classifier::Classifier(Network model) : model(model), m(0), n(0), metrics(Metrics()), fitted(false) {}
|
||||
Classifier& Classifier::build(vector<string>& features, string className, map<string, vector<int>>& 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;
|
||||
m = dataset.size(1);
|
||||
n = dataset.size(0) - 1;
|
||||
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();
|
||||
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, 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<string>& features, string className, map<string, vector<int>>& states)
|
||||
{
|
||||
this->X = X;
|
||||
this->y = y;
|
||||
Xv = vector<vector<int>>();
|
||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
dataset = X;
|
||||
buildDataset(y);
|
||||
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)
|
||||
{
|
||||
Xv = X;
|
||||
generateTensorXFromVector();
|
||||
this->y = torch::tensor(y, kInt32);
|
||||
yv = y;
|
||||
dataset = torch::zeros({ static_cast<int>(X.size()), static_cast<int>(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<string>& features, string className, map<string, vector<int>>& 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");
|
||||
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");
|
||||
@@ -108,7 +112,7 @@ namespace bayesnet {
|
||||
}
|
||||
return model.score(X, y);
|
||||
}
|
||||
vector<string> Classifier::show()
|
||||
vector<string> Classifier::show() const
|
||||
{
|
||||
return model.show();
|
||||
}
|
||||
@@ -120,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;
|
||||
}
|
||||
@@ -137,9 +141,8 @@ namespace bayesnet {
|
||||
{
|
||||
return model.topological_sort();
|
||||
}
|
||||
void Classifier::dump_cpt()
|
||||
void Classifier::dump_cpt() const
|
||||
{
|
||||
model.dump_cpt();
|
||||
}
|
||||
|
||||
}
|
@@ -10,39 +10,37 @@ using namespace torch;
|
||||
namespace bayesnet {
|
||||
class Classifier : public BaseClassifier {
|
||||
private:
|
||||
bool fitted;
|
||||
void buildDataset(torch::Tensor& y);
|
||||
Classifier& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
||||
protected:
|
||||
bool fitted;
|
||||
Network model;
|
||||
int m, n; // m: number of samples, n: number of features
|
||||
Tensor X; // nxm tensor
|
||||
vector<vector<int>> Xv; // nxm vector
|
||||
Tensor y;
|
||||
vector<int> yv;
|
||||
Tensor samples; // (n+1)xm tensor
|
||||
Tensor dataset; // (n+1)xm tensor
|
||||
Metrics metrics;
|
||||
vector<string> features;
|
||||
string className;
|
||||
map<string, vector<int>> states;
|
||||
void checkFitParameters();
|
||||
void generateTensorXFromVector();
|
||||
virtual void train() = 0;
|
||||
virtual void buildModel() = 0;
|
||||
void trainModel() override;
|
||||
public:
|
||||
Classifier(Network model);
|
||||
virtual ~Classifier() = default;
|
||||
Classifier& fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
Classifier& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
Classifier& fit(torch::Tensor& dataset, vector<string>& features, string className, map<string, vector<int>>& 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<int> predict(vector<vector<int>>& X) override;
|
||||
float score(Tensor& X, Tensor& y) override;
|
||||
float score(vector<vector<int>>& X, vector<int>& y) override;
|
||||
vector<string> show() override;
|
||||
vector<string> topological_order() override;
|
||||
void dump_cpt() override;
|
||||
vector<string> show() const override;
|
||||
vector<string> topological_order() override;
|
||||
void dump_cpt() const override;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
@@ -3,54 +3,15 @@
|
||||
namespace bayesnet {
|
||||
using namespace torch;
|
||||
|
||||
Ensemble::Ensemble() : n_models(0), metrics(Metrics()), fitted(false) {}
|
||||
Ensemble& Ensemble::build(vector<string>& features, string className, map<string, vector<int>>& 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<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 = X;
|
||||
this->y = y;
|
||||
Xv = vector<vector<int>>();
|
||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
return build(features, className, states);
|
||||
}
|
||||
Ensemble& Ensemble::fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states)
|
||||
{
|
||||
Xv = X;
|
||||
generateTensorXFromVector();
|
||||
this->y = torch::tensor(y, kInt32);
|
||||
yv = y;
|
||||
return build(features, className, states);
|
||||
}
|
||||
vector<int> Ensemble::voting(Tensor& y_pred)
|
||||
{
|
||||
@@ -132,9 +93,8 @@ namespace bayesnet {
|
||||
}
|
||||
}
|
||||
return (double)correct / y_pred.size();
|
||||
|
||||
}
|
||||
vector<string> Ensemble::show()
|
||||
vector<string> Ensemble::show() const
|
||||
{
|
||||
auto result = vector<string>();
|
||||
for (auto i = 0; i < n_models; ++i) {
|
||||
@@ -143,7 +103,7 @@ namespace bayesnet {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
vector<string> Ensemble::graph(const string& title)
|
||||
vector<string> Ensemble::graph(const string& title) const
|
||||
{
|
||||
auto result = vector<string>();
|
||||
for (auto i = 0; i < n_models; ++i) {
|
||||
@@ -152,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) {
|
||||
@@ -160,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) {
|
||||
@@ -168,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) {
|
||||
|
@@ -8,44 +8,31 @@ using namespace std;
|
||||
using namespace torch;
|
||||
|
||||
namespace bayesnet {
|
||||
class Ensemble : public BaseClassifier {
|
||||
class Ensemble : public Classifier {
|
||||
private:
|
||||
Ensemble& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
||||
protected:
|
||||
unsigned n_models;
|
||||
bool fitted;
|
||||
vector<unique_ptr<Classifier>> models;
|
||||
Tensor X;
|
||||
vector<vector<int>> Xv;
|
||||
Tensor y;
|
||||
vector<int> yv;
|
||||
Tensor samples;
|
||||
Metrics metrics;
|
||||
vector<string> features;
|
||||
string className;
|
||||
map<string, vector<int>> states;
|
||||
void virtual train() = 0;
|
||||
void trainModel() override;
|
||||
vector<int> voting(Tensor& y_pred);
|
||||
void generateTensorXFromVector();
|
||||
public:
|
||||
Ensemble();
|
||||
virtual ~Ensemble() = default;
|
||||
Ensemble& fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
Ensemble& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
vector<int> predict(vector<vector<int>>& X) override;
|
||||
float score(Tensor& X, Tensor& y) override;
|
||||
float score(vector<vector<int>>& X, vector<int>& y) override;
|
||||
int getNumberOfNodes() override;
|
||||
int getNumberOfEdges() override;
|
||||
int getNumberOfStates() override;
|
||||
vector<string> show() override;
|
||||
vector<string> graph(const string& title) override;
|
||||
vector<string> topological_order() override
|
||||
int getNumberOfNodes() const override;
|
||||
int getNumberOfEdges() const override;
|
||||
int getNumberOfStates() const override;
|
||||
vector<string> show() const override;
|
||||
vector<string> graph(const string& title) const override;
|
||||
vector<string> topological_order() override
|
||||
{
|
||||
return vector<string>();
|
||||
}
|
||||
void dump_cpt() override
|
||||
void dump_cpt() const override
|
||||
{
|
||||
}
|
||||
};
|
||||
|
@@ -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 <float> 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
|
||||
@@ -78,7 +79,7 @@ namespace bayesnet {
|
||||
exit_cond = num == n_edges || candidates.size(0) == 0;
|
||||
}
|
||||
}
|
||||
vector<string> KDB::graph(const string& title)
|
||||
vector<string> KDB::graph(const string& title) const
|
||||
{
|
||||
string header{ title };
|
||||
if (title == "KDB") {
|
||||
|
@@ -11,11 +11,11 @@ namespace bayesnet {
|
||||
float theta;
|
||||
void add_m_edges(int idx, vector<int>& S, Tensor& weights);
|
||||
protected:
|
||||
void train() override;
|
||||
void buildModel() override;
|
||||
public:
|
||||
explicit KDB(int k, float theta = 0.03);
|
||||
virtual ~KDB() {};
|
||||
vector<string> graph(const string& name = "KDB") override;
|
||||
vector<string> graph(const string& name = "KDB") const override;
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -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<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...
|
||||
@@ -11,16 +11,11 @@ namespace bayesnet {
|
||||
Xf = X_;
|
||||
y = y_;
|
||||
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
|
||||
fit_local_discretization(states, y);
|
||||
generateTensorXFromVector();
|
||||
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(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);
|
||||
KDB::fit(dataset, features, className, states);
|
||||
states = localDiscretizationProposal(states, model);
|
||||
return *this;
|
||||
}
|
||||
Tensor KDBLd::predict(Tensor& X)
|
||||
@@ -28,7 +23,7 @@ namespace bayesnet {
|
||||
auto Xt = prepareX(X);
|
||||
return KDB::predict(Xt);
|
||||
}
|
||||
vector<string> KDBLd::graph(const string& name)
|
||||
vector<string> KDBLd::graph(const string& name) const
|
||||
{
|
||||
return KDB::graph(name);
|
||||
}
|
||||
|
@@ -11,7 +11,7 @@ namespace bayesnet {
|
||||
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;
|
||||
vector<string> graph(const string& name = "KDB") const override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
|
@@ -94,7 +94,7 @@ namespace bayesnet {
|
||||
return result;
|
||||
}
|
||||
|
||||
MST::MST(vector<string>& features, Tensor& weights, int root) : features(features), weights(weights), root(root) {}
|
||||
MST::MST(const vector<string>& features, const Tensor& weights, const int root) : features(features), weights(weights), root(root) {}
|
||||
vector<pair<int, int>> MST::maximumSpanningTree()
|
||||
{
|
||||
auto num_features = features.size();
|
||||
|
@@ -13,7 +13,7 @@ namespace bayesnet {
|
||||
int root = 0;
|
||||
public:
|
||||
MST() = default;
|
||||
MST(vector<string>& features, Tensor& weights, int root);
|
||||
MST(const vector<string>& features, const Tensor& weights, const int root);
|
||||
vector<pair<int, int>> maximumSpanningTree();
|
||||
};
|
||||
class Graph {
|
||||
|
@@ -20,7 +20,6 @@ namespace bayesnet {
|
||||
classNumStates = 0;
|
||||
fitted = false;
|
||||
nodes.clear();
|
||||
dataset.clear();
|
||||
samples = torch::Tensor();
|
||||
}
|
||||
float Network::getmaxThreads()
|
||||
@@ -44,15 +43,15 @@ namespace bayesnet {
|
||||
}
|
||||
nodes[name] = std::make_unique<Node>(name);
|
||||
}
|
||||
vector<string> Network::getFeatures()
|
||||
vector<string> 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) {
|
||||
@@ -60,7 +59,7 @@ namespace bayesnet {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
string Network::getClassName()
|
||||
string Network::getClassName() const
|
||||
{
|
||||
return className;
|
||||
}
|
||||
@@ -105,7 +104,7 @@ namespace bayesnet {
|
||||
{
|
||||
return nodes;
|
||||
}
|
||||
void Network::checkFitData(int n_samples, int n_features, int n_samples_y, const vector<string>& featureNames, const string& className)
|
||||
void Network::checkFitData(int n_samples, int n_features, int n_samples_y, const vector<string>& featureNames, const string& className, const map<string, vector<int>>& 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) + ")");
|
||||
@@ -123,50 +122,54 @@ 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<string, vector<int>>& states)
|
||||
{
|
||||
// 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);
|
||||
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(torch::Tensor& X, torch::Tensor& y, const vector<string>& featureNames, const string& className)
|
||||
void Network::fit(const torch::Tensor& X, const torch::Tensor& y, const vector<string>& featureNames, const string& className, const map<string, vector<int>>& 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;
|
||||
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<int>(row_feature.data_ptr<int>(), row_feature.data_ptr<int>() + row_feature.size(0));;
|
||||
}
|
||||
dataset[className] = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||
completeFit();
|
||||
completeFit(states);
|
||||
}
|
||||
void Network::fit(const torch::Tensor& samples, const vector<string>& featureNames, const string& className, const map<string, vector<int>>& states)
|
||||
{
|
||||
checkFitData(samples.size(1), samples.size(0) - 1, samples.size(1), featureNames, className, states);
|
||||
this->className = className;
|
||||
this->samples = samples;
|
||||
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<vector<int>>& input_data, const vector<int>& labels, const vector<string>& featureNames, const string& className)
|
||||
void Network::fit(const vector<vector<int>>& input_data, const vector<int>& labels, const vector<string>& featureNames, const string& className, const map<string, vector<int>>& 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;
|
||||
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<int>(input_data.size() + 1), static_cast<int>(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();
|
||||
completeFit(states);
|
||||
}
|
||||
void Network::completeFit()
|
||||
void Network::completeFit(const map<string, vector<int>>& states)
|
||||
{
|
||||
setStates();
|
||||
setStates(states);
|
||||
int maxThreadsRunning = static_cast<int>(std::thread::hardware_concurrency() * maxThreads);
|
||||
if (maxThreadsRunning < 1) {
|
||||
maxThreadsRunning = 1;
|
||||
@@ -188,7 +191,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();
|
||||
@@ -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));
|
||||
@@ -328,12 +331,12 @@ 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();
|
||||
@@ -343,7 +346,7 @@ namespace bayesnet {
|
||||
transform(result.begin(), result.end(), result.begin(), [sum](double& value) { return value / sum; });
|
||||
return result;
|
||||
}
|
||||
vector<string> Network::show()
|
||||
vector<string> Network::show() const
|
||||
{
|
||||
vector<string> result;
|
||||
// Draw the network
|
||||
@@ -356,7 +359,7 @@ namespace bayesnet {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
vector<string> Network::graph(const string& title)
|
||||
vector<string> Network::graph(const string& title) const
|
||||
{
|
||||
auto output = vector<string>();
|
||||
auto prefix = "digraph BayesNet {\nlabel=<BayesNet ";
|
||||
@@ -370,7 +373,7 @@ namespace bayesnet {
|
||||
output.push_back("}\n");
|
||||
return output;
|
||||
}
|
||||
vector<pair<string, string>> Network::getEdges()
|
||||
vector<pair<string, string>> Network::getEdges() const
|
||||
{
|
||||
auto edges = vector<pair<string, string>>();
|
||||
for (const auto& node : nodes) {
|
||||
@@ -382,6 +385,10 @@ namespace bayesnet {
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
int Network::getNumEdges() const
|
||||
{
|
||||
return getEdges().size();
|
||||
}
|
||||
vector<string> Network::topological_sort()
|
||||
{
|
||||
/* Check if al the fathers of every node are before the node */
|
||||
@@ -420,7 +427,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;
|
||||
|
@@ -8,11 +8,10 @@ namespace bayesnet {
|
||||
class Network {
|
||||
private:
|
||||
map<string, unique_ptr<Node>> nodes;
|
||||
map<string, vector<int>> dataset;
|
||||
bool fitted;
|
||||
float maxThreads = 0.95;
|
||||
int classNumStates;
|
||||
vector<string> features; // Including class
|
||||
vector<string> features; // Including classname
|
||||
string className;
|
||||
int laplaceSmoothing = 1;
|
||||
torch::Tensor samples; // nxm tensor used to fit the model
|
||||
@@ -21,13 +20,9 @@ namespace bayesnet {
|
||||
vector<double> predict_sample(const torch::Tensor&);
|
||||
vector<double> exactInference(map<string, int>&);
|
||||
double computeFactor(map<string, int>&);
|
||||
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<string>& featureNames, const string& className);
|
||||
void setStates();
|
||||
void completeFit(const map<string, vector<int>>&);
|
||||
void checkFitData(int n_features, int n_samples, int n_samples_y, const vector<string>& featureNames, const string& className, const map<string, vector<int>>&);
|
||||
void setStates(const map<string, vector<int>>&);
|
||||
public:
|
||||
Network();
|
||||
explicit Network(float, int);
|
||||
@@ -38,26 +33,26 @@ namespace bayesnet {
|
||||
void addNode(const string&);
|
||||
void addEdge(const string&, const string&);
|
||||
map<string, std::unique_ptr<Node>>& getNodes();
|
||||
vector<string> getFeatures();
|
||||
int getStates();
|
||||
vector<pair<string, string>> getEdges();
|
||||
int getClassNumStates();
|
||||
string getClassName();
|
||||
void fit(const vector<vector<int>>&, const vector<int>&, const vector<string>&, const string&);
|
||||
void fit(torch::Tensor&, torch::Tensor&, const vector<string>&, const string&);
|
||||
vector<string> getFeatures() const;
|
||||
int getStates() const;
|
||||
vector<pair<string, string>> getEdges() const;
|
||||
int getNumEdges() const;
|
||||
int getClassNumStates() const;
|
||||
string getClassName() const;
|
||||
void fit(const vector<vector<int>>&, const vector<int>&, const vector<string>&, const string&, const map<string, vector<int>>&);
|
||||
void fit(const torch::Tensor&, const torch::Tensor&, const vector<string>&, const string&, const map<string, vector<int>>&);
|
||||
void fit(const torch::Tensor&, const vector<string>&, const string&, const map<string, vector<int>>&);
|
||||
vector<int> predict(const vector<vector<int>>&); // 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<vector<double>> predict_proba(const vector<vector<int>>&); // Return mxn vector of probabilities
|
||||
torch::Tensor predict_proba(const torch::Tensor&); // Return mxn tensor of probabilities
|
||||
double score(const vector<vector<int>>&, const vector<int>&);
|
||||
vector<string> topological_sort();
|
||||
vector<string> show();
|
||||
vector<string> graph(const string& title); // Returns a vector of strings representing the graph in graphviz format
|
||||
vector<string> show() const;
|
||||
vector<string> 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"; }
|
||||
};
|
||||
}
|
||||
|
@@ -84,7 +84,7 @@ namespace bayesnet {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void Node::computeCPT(map<string, vector<int>>& dataset, const int laplaceSmoothing)
|
||||
void Node::computeCPT(const torch::Tensor& dataset, const vector<string>& 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<c10::optional<torch::Tensor>> 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);
|
||||
}
|
||||
|
@@ -26,7 +26,7 @@ namespace bayesnet {
|
||||
vector<Node*>& getParents();
|
||||
vector<Node*>& getChildren();
|
||||
torch::Tensor& getCPT();
|
||||
void computeCPT(map<string, vector<int>>&, const int);
|
||||
void computeCPT(const torch::Tensor&, const vector<string>&, const int);
|
||||
int getNumStates() const;
|
||||
void setNumStates(int);
|
||||
unsigned minFill();
|
||||
|
@@ -2,21 +2,21 @@
|
||||
#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(torch::Tensor& dataset_, vector<string>& features_, string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_) {}
|
||||
Proposal::~Proposal()
|
||||
{
|
||||
for (auto& [key, value] : discretizers) {
|
||||
delete value;
|
||||
}
|
||||
}
|
||||
void Proposal::localDiscretizationProposal(map<string, vector<int>>& states, Network& model)
|
||||
map<string, vector<int>> Proposal::localDiscretizationProposal(const map<string, vector<int>>& oldStates, 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();
|
||||
map<string, vector<int>> states = oldStates;
|
||||
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();
|
||||
@@ -30,13 +30,13 @@ namespace bayesnet {
|
||||
parents.erase(remove(parents.begin(), parents.end(), pClassName), parents.end());
|
||||
// Get the indices of the parents
|
||||
vector<int> 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<string> yJoinParents;
|
||||
transform(yv.begin(), yv.end(), back_inserter(yJoinParents), [&](const auto& p) {return to_string(p); });
|
||||
vector<string> yJoinParents(Xf.size(1));
|
||||
for (auto idx : indices) {
|
||||
for (int i = 0; i < n_samples; ++i) {
|
||||
yJoinParents[i] += to_string(Xv[idx][i]);
|
||||
for (int i = 0; i < Xf.size(1); ++i) {
|
||||
yJoinParents[i] += to_string(pDataset.index({ idx, i }).item<int>());
|
||||
}
|
||||
}
|
||||
auto arff = ArffFiles();
|
||||
@@ -59,26 +59,31 @@ namespace bayesnet {
|
||||
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);
|
||||
pDataset.index_put_({ index, "..." }, torch::tensor(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;
|
||||
}
|
||||
model.fit(pDataset, pFeatures, pClassName, states);
|
||||
}
|
||||
return states;
|
||||
}
|
||||
void Proposal::fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y)
|
||||
map<string, vector<int>> Proposal::fit_local_discretization(const 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 the continuous input data and build pDataset (Classifier::dataset)
|
||||
int m = Xf.size(1);
|
||||
int n = Xf.size(0);
|
||||
map<string, vector<int>> states;
|
||||
pDataset = torch::zeros({ n + 1, m }, kInt32);
|
||||
auto 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) {
|
||||
for (auto 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));
|
||||
pDataset.index_put_({ i, "..." }, torch::tensor(discretizer->transform(Xt)));
|
||||
auto xStates = vector<int>(discretizer->getCutPoints().size() + 1);
|
||||
iota(xStates.begin(), xStates.end(), 0);
|
||||
states[pFeatures[i]] = xStates;
|
||||
@@ -88,6 +93,8 @@ namespace bayesnet {
|
||||
auto yStates = vector<int>(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)
|
||||
{
|
||||
|
@@ -10,19 +10,19 @@
|
||||
namespace bayesnet {
|
||||
class Proposal {
|
||||
public:
|
||||
Proposal(vector<vector<int>>& Xv_, vector<int>& yv_, vector<string>& features_, string& className_);
|
||||
Proposal(torch::Tensor& pDataset, 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);
|
||||
map<string, vector<int>> localDiscretizationProposal(const map<string, vector<int>>& states, Network& model);
|
||||
map<string, vector<int>> fit_local_discretization(const torch::Tensor& y);
|
||||
torch::Tensor Xf; // X continuous nxm tensor
|
||||
torch::Tensor y; // y discrete nx1 tensor
|
||||
map<string, mdlp::CPPFImdlp*> discretizers;
|
||||
private:
|
||||
torch::Tensor& pDataset; // (n+1)xm tensor
|
||||
vector<string>& pFeatures;
|
||||
string& pClassName;
|
||||
vector<vector<int>>& Xv; // X discrete nxm vector
|
||||
vector<int>& yv;
|
||||
};
|
||||
}
|
||||
|
||||
|
@@ -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();
|
||||
@@ -17,7 +17,7 @@ namespace bayesnet {
|
||||
}
|
||||
}
|
||||
}
|
||||
vector<string> SPODE::graph(const string& name)
|
||||
vector<string> SPODE::graph(const string& name) const
|
||||
{
|
||||
return model.graph(name);
|
||||
}
|
||||
|
@@ -7,11 +7,11 @@ namespace bayesnet {
|
||||
private:
|
||||
int root;
|
||||
protected:
|
||||
void train() override;
|
||||
void buildModel() override;
|
||||
public:
|
||||
explicit SPODE(int root);
|
||||
virtual ~SPODE() {};
|
||||
vector<string> graph(const string& name = "SPODE") override;
|
||||
vector<string> graph(const string& name = "SPODE") const override;
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -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<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...
|
||||
@@ -11,24 +11,36 @@ namespace bayesnet {
|
||||
Xf = X_;
|
||||
y = y_;
|
||||
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
|
||||
fit_local_discretization(states, y);
|
||||
generateTensorXFromVector();
|
||||
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(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);
|
||||
SPODE::fit(dataset, features, className, states);
|
||||
states = localDiscretizationProposal(states, model);
|
||||
return *this;
|
||||
}
|
||||
SPODELd& SPODELd::fit(torch::Tensor& dataset, vector<string>& features_, string className_, map<string, vector<int>>& 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
|
||||
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);
|
||||
states = localDiscretizationProposal(states, model);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Tensor SPODELd::predict(Tensor& X)
|
||||
{
|
||||
auto Xt = prepareX(X);
|
||||
return SPODE::predict(Xt);
|
||||
}
|
||||
vector<string> SPODELd::graph(const string& name)
|
||||
vector<string> SPODELd::graph(const string& name) const
|
||||
{
|
||||
return SPODE::graph(name);
|
||||
}
|
||||
|
@@ -6,12 +6,12 @@
|
||||
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;
|
||||
SPODELd& fit(torch::Tensor& dataset, vector<string>& features, string className, map<string, vector<int>>& states) override;
|
||||
vector<string> graph(const string& name = "SPODE") const override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
|
@@ -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 <pair<int, float >>();
|
||||
Tensor class_dataset = samples.index({ -1, "..." });
|
||||
Tensor class_dataset = dataset.index({ -1, "..." });
|
||||
for (int i = 0; i < static_cast<int>(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 });
|
||||
}
|
||||
@@ -34,7 +34,7 @@ namespace bayesnet {
|
||||
model.addEdge(className, feature);
|
||||
}
|
||||
}
|
||||
vector<string> TAN::graph(const string& title)
|
||||
vector<string> TAN::graph(const string& title) const
|
||||
{
|
||||
return model.graph(title);
|
||||
}
|
||||
|
@@ -7,11 +7,11 @@ namespace bayesnet {
|
||||
class TAN : public Classifier {
|
||||
private:
|
||||
protected:
|
||||
void train() override;
|
||||
void buildModel() override;
|
||||
public:
|
||||
TAN();
|
||||
virtual ~TAN() {};
|
||||
vector<string> graph(const string& name = "TAN") override;
|
||||
vector<string> graph(const string& name = "TAN") const override;
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -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<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...
|
||||
@@ -11,24 +11,20 @@ namespace bayesnet {
|
||||
Xf = X_;
|
||||
y = y_;
|
||||
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
|
||||
fit_local_discretization(states, y);
|
||||
generateTensorXFromVector();
|
||||
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(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);
|
||||
TAN::fit(dataset, features, className, states);
|
||||
states = localDiscretizationProposal(states, model);
|
||||
return *this;
|
||||
|
||||
}
|
||||
Tensor TANLd::predict(Tensor& X)
|
||||
{
|
||||
auto Xt = prepareX(X);
|
||||
return TAN::predict(Xt);
|
||||
}
|
||||
vector<string> TANLd::graph(const string& name)
|
||||
vector<string> TANLd::graph(const string& name) const
|
||||
{
|
||||
return TAN::graph(name);
|
||||
}
|
||||
|
@@ -11,7 +11,7 @@ namespace bayesnet {
|
||||
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;
|
||||
vector<string> graph(const string& name = "TAN") const override;
|
||||
Tensor predict(Tensor& X) override;
|
||||
static inline string version() { return "0.0.1"; };
|
||||
};
|
||||
|
10
src/Platform/BestResult.h
Normal file
10
src/Platform/BestResult.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#ifndef BESTRESULT_H
|
||||
#define BESTRESULT_H
|
||||
#include <string>
|
||||
class BestResult {
|
||||
public:
|
||||
static std::string title() { return "STree_default (linear-ovo)"; }
|
||||
static double score() { return 22.109799; }
|
||||
static std::string scoreName() { return "accuracy"; }
|
||||
};
|
||||
#endif
|
@@ -5,4 +5,6 @@ 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 Report.cc)
|
||||
add_executable(manage manage.cc Results.cc Report.cc)
|
||||
target_link_libraries(main BayesNet ArffFiles mdlp "${TORCH_LIBRARIES}")
|
||||
target_link_libraries(manage "${TORCH_LIBRARIES}")
|
14
src/Platform/Colors.h
Normal file
14
src/Platform/Colors.h
Normal file
@@ -0,0 +1,14 @@
|
||||
#ifndef COLORS_H
|
||||
#define COLORS_H
|
||||
class Colors {
|
||||
public:
|
||||
static std::string MAGENTA() { return "\033[1;35m"; }
|
||||
static std::string BLUE() { return "\033[1;34m"; }
|
||||
static std::string CYAN() { return "\033[1;36m"; }
|
||||
static std::string GREEN() { return "\033[1;32m"; }
|
||||
static std::string YELLOW() { return "\033[1;33m"; }
|
||||
static std::string RED() { return "\033[1;31m"; }
|
||||
static std::string WHITE() { return "\033[1;37m"; }
|
||||
static std::string RESET() { return "\033[0m"; }
|
||||
};
|
||||
#endif // COLORS_H
|
10
src/Platform/Paths.h
Normal file
10
src/Platform/Paths.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#ifndef PATHS_H
|
||||
#define PATHS_H
|
||||
namespace platform {
|
||||
class Paths {
|
||||
public:
|
||||
static std::string datasets() { return "datasets/"; }
|
||||
static std::string results() { return "results/"; }
|
||||
};
|
||||
}
|
||||
#endif
|
@@ -1,9 +1,11 @@
|
||||
#include "Report.h"
|
||||
#include "BestResult.h"
|
||||
|
||||
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 +15,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,16 +23,17 @@ 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()
|
||||
{
|
||||
header();
|
||||
body();
|
||||
footer();
|
||||
}
|
||||
void Report::header()
|
||||
{
|
||||
cout << string(MAXL, '*') << endl;
|
||||
cout << Colors::MAGENTA() << 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"));
|
||||
@@ -41,26 +44,50 @@ namespace platform {
|
||||
}
|
||||
void Report::body()
|
||||
{
|
||||
cout << "Dataset Sampl. Feat. Cls Nodes Edges States Score Time Hyperparameters" << endl;
|
||||
cout << "============================== ====== ===== === ======= ======= ======= =============== ================= ===============" << endl;
|
||||
cout << Colors::GREEN() << "Dataset Sampl. Feat. Cls Nodes Edges States Score Time Hyperparameters" << endl;
|
||||
cout << "============================== ====== ===== === ======= ======= ======= =============== ================== ===============" << endl;
|
||||
json lastResult;
|
||||
totalScore = 0;
|
||||
bool odd = true;
|
||||
for (const auto& r : data["results"]) {
|
||||
cout << setw(30) << left << r["dataset"].get<string>() << " ";
|
||||
auto color = odd ? Colors::CYAN() : Colors::BLUE();
|
||||
cout << color << 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 << setw(8) << right << setprecision(6) << fixed << r["score"].get<double>() << "±" << setw(6) << setprecision(4) << fixed << r["score_std"].get<double>() << " ";
|
||||
cout << setw(11) << right << setprecision(6) << fixed << r["time"].get<double>() << "±" << setw(6) << setprecision(4) << fixed << r["time_std"].get<double>() << " ";
|
||||
try {
|
||||
cout << r["hyperparameters"].get<string>();
|
||||
}
|
||||
catch (const exception& err) {
|
||||
cout << r["hyperparameters"];
|
||||
}
|
||||
cout << endl;
|
||||
lastResult = r;
|
||||
totalScore += r["score"].get<double>();
|
||||
odd = !odd;
|
||||
}
|
||||
if (data["results"].size() == 1) {
|
||||
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 << headerLine("Train scores: " + fVector(lastResult["scores_train"]));
|
||||
cout << headerLine("Test scores: " + fVector(lastResult["scores_test"]));
|
||||
cout << headerLine("Train times: " + fVector(lastResult["times_train"]));
|
||||
cout << headerLine("Test times: " + fVector(lastResult["times_test"]));
|
||||
cout << string(MAXL, '*') << endl;
|
||||
}
|
||||
}
|
||||
void Report::footer()
|
||||
{
|
||||
cout << Colors::MAGENTA() << string(MAXL, '*') << endl;
|
||||
auto score = data["score_name"].get<string>();
|
||||
if (score == BestResult::scoreName()) {
|
||||
cout << headerLine(score + " compared to " + BestResult::title() + " .: " + to_string(totalScore / BestResult::score()));
|
||||
}
|
||||
cout << string(MAXL, '*') << endl << Colors::RESET();
|
||||
|
||||
}
|
||||
}
|
@@ -3,6 +3,7 @@
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "Colors.h"
|
||||
|
||||
using json = nlohmann::json;
|
||||
const int MAXL = 121;
|
||||
@@ -16,8 +17,10 @@ namespace platform {
|
||||
private:
|
||||
void header();
|
||||
void body();
|
||||
void footer();
|
||||
string fromVector(const string& key);
|
||||
json data;
|
||||
double totalScore; // Total score of all results in a report
|
||||
};
|
||||
};
|
||||
#endif
|
239
src/Platform/Results.cc
Normal file
239
src/Platform/Results.cc
Normal file
@@ -0,0 +1,239 @@
|
||||
#include <filesystem>
|
||||
#include "platformUtils.h"
|
||||
#include "Results.h"
|
||||
#include "Report.h"
|
||||
#include "BestResult.h"
|
||||
#include "Colors.h"
|
||||
namespace platform {
|
||||
Result::Result(const string& path, const string& filename)
|
||||
: path(path)
|
||||
, filename(filename)
|
||||
{
|
||||
auto data = load();
|
||||
date = data["date"];
|
||||
score = 0;
|
||||
for (const auto& result : data["results"]) {
|
||||
score += result["score"].get<double>();
|
||||
}
|
||||
scoreName = data["score_name"];
|
||||
if (scoreName == BestResult::scoreName()) {
|
||||
score /= BestResult::score();
|
||||
}
|
||||
title = data["title"];
|
||||
duration = data["duration"];
|
||||
model = data["model"];
|
||||
}
|
||||
json Result::load() const
|
||||
{
|
||||
ifstream resultData(path + "/" + filename);
|
||||
if (resultData.is_open()) {
|
||||
json data = json::parse(resultData);
|
||||
return data;
|
||||
}
|
||||
throw invalid_argument("Unable to open result file. [" + path + "/" + filename + "]");
|
||||
}
|
||||
void Results::load()
|
||||
{
|
||||
using std::filesystem::directory_iterator;
|
||||
for (const auto& file : directory_iterator(path)) {
|
||||
auto filename = file.path().filename().string();
|
||||
if (filename.find(".json") != string::npos && filename.find("results_") == 0) {
|
||||
auto result = Result(path, filename);
|
||||
bool addResult = true;
|
||||
if (model != "any" && result.getModel() != model || scoreName != "any" && scoreName != result.getScoreName())
|
||||
addResult = false;
|
||||
if (addResult)
|
||||
files.push_back(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
string Result::to_string() const
|
||||
{
|
||||
stringstream oss;
|
||||
oss << date << " ";
|
||||
oss << setw(12) << left << model << " ";
|
||||
oss << setw(11) << left << scoreName << " ";
|
||||
oss << right << setw(11) << setprecision(7) << fixed << score << " ";
|
||||
oss << setw(9) << setprecision(3) << fixed << duration << " ";
|
||||
oss << setw(50) << left << title << " ";
|
||||
return oss.str();
|
||||
}
|
||||
void Results::show() const
|
||||
{
|
||||
cout << Colors::GREEN() << "Results found: " << files.size() << endl;
|
||||
cout << "-------------------" << endl;
|
||||
auto i = 0;
|
||||
cout << " # Date Model Score Name Score Duration Title" << endl;
|
||||
cout << "=== ========== ============ =========== =========== ========= =============================================================" << endl;
|
||||
bool odd = true;
|
||||
for (const auto& result : files) {
|
||||
auto color = odd ? Colors::BLUE() : Colors::CYAN();
|
||||
cout << color << setw(3) << fixed << right << i++ << " ";
|
||||
cout << result.to_string() << endl;
|
||||
if (i == max && max != 0) {
|
||||
break;
|
||||
}
|
||||
odd = !odd;
|
||||
}
|
||||
}
|
||||
int Results::getIndex(const string& intent) const
|
||||
{
|
||||
string color;
|
||||
if (intent == "delete") {
|
||||
color = Colors::RED();
|
||||
} else {
|
||||
color = Colors::YELLOW();
|
||||
}
|
||||
cout << color << "Choose result to " << intent << " (cancel=-1): ";
|
||||
string line;
|
||||
getline(cin, line);
|
||||
int index = stoi(line);
|
||||
if (index >= -1 && index < static_cast<int>(files.size())) {
|
||||
return index;
|
||||
}
|
||||
cout << "Invalid index" << endl;
|
||||
return -1;
|
||||
}
|
||||
void Results::report(const int index) const
|
||||
{
|
||||
cout << Colors::YELLOW() << "Reporting " << files.at(index).getFilename() << endl;
|
||||
auto data = files.at(index).load();
|
||||
Report report(data);
|
||||
report.show();
|
||||
}
|
||||
void Results::menu()
|
||||
{
|
||||
char option;
|
||||
int index;
|
||||
bool finished = false;
|
||||
string filename, line, options = "qldhsr";
|
||||
while (!finished) {
|
||||
cout << Colors::RESET() << "Choose option (quit='q', list='l', delete='d', hide='h', sort='s', report='r'): ";
|
||||
getline(cin, line);
|
||||
if (line.size() == 0)
|
||||
continue;
|
||||
if (options.find(line[0]) != string::npos) {
|
||||
if (line.size() > 1) {
|
||||
cout << "Invalid option" << endl;
|
||||
continue;
|
||||
}
|
||||
option = line[0];
|
||||
} else {
|
||||
index = stoi(line);
|
||||
if (index >= 0 && index < files.size()) {
|
||||
report(index);
|
||||
} else {
|
||||
cout << "Invalid option" << endl;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
switch (option) {
|
||||
case 'q':
|
||||
finished = true;
|
||||
break;
|
||||
case 'l':
|
||||
show();
|
||||
break;
|
||||
case 'd':
|
||||
index = getIndex("delete");
|
||||
if (index == -1)
|
||||
break;
|
||||
filename = files[index].getFilename();
|
||||
cout << "Deleting " << filename << endl;
|
||||
remove((path + "/" + filename).c_str());
|
||||
files.erase(files.begin() + index);
|
||||
cout << "File: " + filename + " deleted!" << endl;
|
||||
show();
|
||||
break;
|
||||
case 'h':
|
||||
index = getIndex("hide");
|
||||
if (index == -1)
|
||||
break;
|
||||
filename = files[index].getFilename();
|
||||
cout << "Hiding " << filename << endl;
|
||||
rename((path + "/" + filename).c_str(), (path + "/." + filename).c_str());
|
||||
files.erase(files.begin() + index);
|
||||
show();
|
||||
menu();
|
||||
break;
|
||||
case 's':
|
||||
sortList();
|
||||
show();
|
||||
break;
|
||||
case 'r':
|
||||
index = getIndex("report");
|
||||
if (index == -1)
|
||||
break;
|
||||
report(index);
|
||||
break;
|
||||
default:
|
||||
cout << "Invalid option" << endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
void Results::sortList()
|
||||
{
|
||||
cout << Colors::YELLOW() << "Choose sorting field (date='d', score='s', duration='u', model='m'): ";
|
||||
string line;
|
||||
char option;
|
||||
getline(cin, line);
|
||||
if (line.size() == 0)
|
||||
return;
|
||||
if (line.size() > 1) {
|
||||
cout << "Invalid option" << endl;
|
||||
return;
|
||||
}
|
||||
option = line[0];
|
||||
switch (option) {
|
||||
case 'd':
|
||||
sortDate();
|
||||
break;
|
||||
case 's':
|
||||
sortScore();
|
||||
break;
|
||||
case 'u':
|
||||
sortDuration();
|
||||
break;
|
||||
case 'm':
|
||||
sortModel();
|
||||
break;
|
||||
default:
|
||||
cout << "Invalid option" << endl;
|
||||
}
|
||||
}
|
||||
void Results::sortDate()
|
||||
{
|
||||
sort(files.begin(), files.end(), [](const Result& a, const Result& b) {
|
||||
return a.getDate() > b.getDate();
|
||||
});
|
||||
}
|
||||
void Results::sortModel()
|
||||
{
|
||||
sort(files.begin(), files.end(), [](const Result& a, const Result& b) {
|
||||
return a.getModel() > b.getModel();
|
||||
});
|
||||
}
|
||||
void Results::sortDuration()
|
||||
{
|
||||
sort(files.begin(), files.end(), [](const Result& a, const Result& b) {
|
||||
return a.getDuration() > b.getDuration();
|
||||
});
|
||||
}
|
||||
void Results::sortScore()
|
||||
{
|
||||
sort(files.begin(), files.end(), [](const Result& a, const Result& b) {
|
||||
return a.getScore() > b.getScore();
|
||||
});
|
||||
}
|
||||
void Results::manage()
|
||||
{
|
||||
if (files.size() == 0) {
|
||||
cout << "No results found!" << endl;
|
||||
exit(0);
|
||||
}
|
||||
show();
|
||||
menu();
|
||||
cout << "Done!" << endl;
|
||||
}
|
||||
|
||||
}
|
56
src/Platform/Results.h
Normal file
56
src/Platform/Results.h
Normal file
@@ -0,0 +1,56 @@
|
||||
#ifndef RESULTS_H
|
||||
#define RESULTS_H
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <nlohmann/json.hpp>
|
||||
namespace platform {
|
||||
using namespace std;
|
||||
using json = nlohmann::json;
|
||||
|
||||
class Result {
|
||||
public:
|
||||
Result(const string& path, const string& filename);
|
||||
json load() const;
|
||||
string to_string() const;
|
||||
string getFilename() const { return filename; };
|
||||
string getDate() const { return date; };
|
||||
double getScore() const { return score; };
|
||||
string getTitle() const { return title; };
|
||||
double getDuration() const { return duration; };
|
||||
string getModel() const { return model; };
|
||||
string getScoreName() const { return scoreName; };
|
||||
private:
|
||||
string path;
|
||||
string filename;
|
||||
string date;
|
||||
double score;
|
||||
string title;
|
||||
double duration;
|
||||
string model;
|
||||
string scoreName;
|
||||
};
|
||||
class Results {
|
||||
public:
|
||||
Results(const string& path, const int max, const string& model, const string& score) : path(path), max(max), model(model), scoreName(score) { load(); };
|
||||
void manage();
|
||||
private:
|
||||
string path;
|
||||
int max;
|
||||
string model;
|
||||
string scoreName;
|
||||
vector<Result> files;
|
||||
void load(); // Loads the list of results
|
||||
void show() const;
|
||||
void report(const int index) const;
|
||||
int getIndex(const string& intent) const;
|
||||
void menu();
|
||||
void sortList();
|
||||
void sortDate();
|
||||
void sortScore();
|
||||
void sortModel();
|
||||
void sortDuration();
|
||||
};
|
||||
};
|
||||
|
||||
#endif
|
@@ -6,20 +6,19 @@
|
||||
#include "DotEnv.h"
|
||||
#include "Models.h"
|
||||
#include "modelRegister.h"
|
||||
#include "Paths.h"
|
||||
|
||||
|
||||
using namespace std;
|
||||
const string PATH_RESULTS = "results";
|
||||
const string PATH_DATASETS = "datasets";
|
||||
|
||||
argparse::ArgumentParser manageArguments(int argc, char** argv)
|
||||
{
|
||||
auto env = platform::DotEnv();
|
||||
argparse::ArgumentParser program("BayesNetSample");
|
||||
argparse::ArgumentParser program("main");
|
||||
program.add_argument("-d", "--dataset").default_value("").help("Dataset file name");
|
||||
program.add_argument("-p", "--path")
|
||||
.help("folder where the data files are located, default")
|
||||
.default_value(string{ PATH_DATASETS }
|
||||
);
|
||||
.default_value(string{ platform::Paths::datasets() });
|
||||
program.add_argument("-m", "--model")
|
||||
.help("Model to use " + platform::Models::instance()->toString())
|
||||
.action([](const std::string& value) {
|
||||
@@ -115,7 +114,7 @@ int main(int argc, char** argv)
|
||||
experiment.go(filesToTest, path);
|
||||
experiment.setDuration(timer.getDuration());
|
||||
if (saveResults)
|
||||
experiment.save(PATH_RESULTS);
|
||||
experiment.save(platform::Paths::results());
|
||||
else
|
||||
experiment.report();
|
||||
cout << "Done!" << endl;
|
||||
|
41
src/Platform/manage.cc
Normal file
41
src/Platform/manage.cc
Normal file
@@ -0,0 +1,41 @@
|
||||
#include <iostream>
|
||||
#include <argparse/argparse.hpp>
|
||||
#include "platformUtils.h"
|
||||
#include "Paths.h"
|
||||
#include "Results.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
argparse::ArgumentParser manageArguments(int argc, char** argv)
|
||||
{
|
||||
argparse::ArgumentParser program("manage");
|
||||
program.add_argument("-n", "--number").default_value(0).help("Number of results to show (0 = all)").scan<'i', int>();
|
||||
program.add_argument("-m", "--model").default_value("any").help("Filter results of the selected model)");
|
||||
program.add_argument("-s", "--score").default_value("any").help("Filter results of the score name supplied");
|
||||
try {
|
||||
program.parse_args(argc, argv);
|
||||
auto number = program.get<int>("number");
|
||||
if (number < 0) {
|
||||
throw runtime_error("Number of results must be greater than or equal to 0");
|
||||
}
|
||||
auto model = program.get<string>("model");
|
||||
auto score = program.get<string>("score");
|
||||
}
|
||||
catch (const exception& err) {
|
||||
cerr << err.what() << endl;
|
||||
cerr << program;
|
||||
exit(1);
|
||||
}
|
||||
return program;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
auto program = manageArguments(argc, argv);
|
||||
auto number = program.get<int>("number");
|
||||
auto model = program.get<string>("model");
|
||||
auto score = program.get<string>("score");
|
||||
auto results = platform::Results(platform::Paths::results(), number, model, score);
|
||||
results.manage();
|
||||
return 0;
|
||||
}
|
@@ -1,4 +1,5 @@
|
||||
#include "platformUtils.h"
|
||||
#include "Paths.h"
|
||||
|
||||
using namespace torch;
|
||||
|
||||
@@ -85,7 +86,7 @@ tuple<Tensor, Tensor, vector<string>, string, map<string, vector<int>>> loadData
|
||||
tuple<vector<vector<int>>, vector<int>, vector<string>, string, map<string, vector<int>>> loadFile(const string& name)
|
||||
{
|
||||
auto handler = ArffFiles();
|
||||
handler.load(PATH + static_cast<string>(name) + ".arff");
|
||||
handler.load(platform::Paths::datasets() + static_cast<string>(name) + ".arff");
|
||||
// Get Dataset X, y
|
||||
vector<mdlp::samples_t>& X = handler.getX();
|
||||
mdlp::labels_t& y = handler.getY();
|
||||
|
Reference in New Issue
Block a user