Compare commits

...

5 Commits

Author SHA1 Message Date
182b52a887 Add states as result in Proposal methods 2023-08-12 16:16:17 +02:00
405887f833 Solved Ld poor results 2023-08-12 11:49:18 +02:00
3a85481a5a Redo pass states to Network Fit needed in crossval
fix mistake in headerline (report)
2023-08-12 11:10:53 +02:00
0ad5505c16 Spodeld working with poor accuracy 2023-08-10 02:06:18 +02:00
323444b74a const functions 2023-08-08 01:53:41 +02:00
28 changed files with 157 additions and 126 deletions

3
.vscode/launch.json vendored
View File

@@ -25,8 +25,7 @@
"program": "${workspaceFolder}/build/src/Platform/main", "program": "${workspaceFolder}/build/src/Platform/main",
"args": [ "args": [
"-m", "-m",
"AODE", "SPODELd",
"--discretize",
"-p", "-p",
"/Users/rmontanana/Code/discretizbench/datasets", "/Users/rmontanana/Code/discretizbench/datasets",
"--stratified", "--stratified",

View File

@@ -9,7 +9,7 @@ namespace bayesnet {
models.push_back(std::make_unique<SPODE>(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); return Ensemble::graph(title);
} }

View File

@@ -9,7 +9,7 @@ namespace bayesnet {
public: public:
AODE(); AODE();
virtual ~AODE() {}; virtual ~AODE() {};
vector<string> graph(const string& title = "AODE") override; vector<string> graph(const string& title = "AODE") const override;
}; };
} }
#endif #endif

View File

@@ -1,18 +1,23 @@
#include "AODELd.h" #include "AODELd.h"
#include "Models.h"
namespace bayesnet { namespace bayesnet {
using namespace std; using namespace std;
AODELd::AODELd() : Ensemble(), Proposal(dataset, 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_) 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_; features = features_;
className = className_; className = className_;
states = states_; Xf = X_;
buildModel(); y = y_;
trainModel(); // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
n_models = models.size(); states = fit_local_discretization(y);
fitted = true; // 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; return *this;
} }
void AODELd::buildModel() void AODELd::buildModel()
{ {
@@ -20,18 +25,15 @@ namespace bayesnet {
for (int i = 0; i < features.size(); ++i) { for (int i = 0; i < features.size(); ++i) {
models.push_back(std::make_unique<SPODELd>(i)); models.push_back(std::make_unique<SPODELd>(i));
} }
n_models = models.size();
} }
void AODELd::trainModel() void AODELd::trainModel()
{ {
for (const auto& model : models) { for (const auto& model : models) {
model->fit(dataset, features, className, states); model->fit(Xf, y, features, className, states);
} }
} }
Tensor AODELd::predict(Tensor& X) vector<string> AODELd::graph(const string& name) const
{
return Ensemble::predict(X);
}
vector<string> AODELd::graph(const string& name)
{ {
return Ensemble::graph(name); return Ensemble::graph(name);
} }

View File

@@ -7,15 +7,14 @@
namespace bayesnet { namespace bayesnet {
using namespace std; using namespace std;
class AODELd : public Ensemble, public Proposal { class AODELd : public Ensemble, public Proposal {
private: protected:
void trainModel() override; void trainModel() override;
void buildModel() override; void buildModel() override;
public: public:
AODELd(); AODELd();
AODELd& fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_) override;
virtual ~AODELd() = default; 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") const override;
vector<string> graph(const string& name = "AODE") override;
Tensor predict(Tensor& X) override;
static inline string version() { return "0.0.1"; }; static inline string version() { return "0.0.1"; };
}; };
} }

View File

@@ -5,6 +5,8 @@
namespace bayesnet { namespace bayesnet {
using namespace std; using namespace std;
class BaseClassifier { class BaseClassifier {
protected:
virtual void trainModel() = 0;
public: public:
// X is nxm vector, y is nx1 vector // 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; virtual BaseClassifier& fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states) = 0;
@@ -16,14 +18,14 @@ namespace bayesnet {
vector<int> virtual predict(vector<vector<int>>& 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(vector<vector<int>>& X, vector<int>& y) = 0;
float virtual score(torch::Tensor& X, torch::Tensor& y) = 0; float virtual score(torch::Tensor& X, torch::Tensor& y) = 0;
int virtual getNumberOfNodes() = 0; int virtual getNumberOfNodes()const = 0;
int virtual getNumberOfEdges() = 0; int virtual getNumberOfEdges()const = 0;
int virtual getNumberOfStates() = 0; int virtual getNumberOfStates() const = 0;
vector<string> virtual show() = 0; vector<string> virtual show() const = 0;
vector<string> virtual graph(const string& title = "") = 0; vector<string> virtual graph(const string& title = "") const = 0;
const string inline getVersion() const { return "0.1.0"; }; const string inline getVersion() const { return "0.1.0"; };
vector<string> virtual topological_order() = 0; vector<string> virtual topological_order() = 0;
void virtual dump_cpt() = 0; void virtual dump_cpt()const = 0;
}; };
} }
#endif #endif

View File

@@ -1,5 +1,7 @@
include_directories(${BayesNet_SOURCE_DIR}/lib/mdlp) include_directories(${BayesNet_SOURCE_DIR}/lib/mdlp)
include_directories(${BayesNet_SOURCE_DIR}/lib/Files) 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 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}") target_link_libraries(BayesNet mdlp ArffFiles "${TORCH_LIBRARIES}")

View File

@@ -37,7 +37,7 @@ namespace bayesnet {
} }
void Classifier::trainModel() void Classifier::trainModel()
{ {
model.fit(dataset, features, className); model.fit(dataset, features, className, states);
} }
// X is nxm where n is the number of features and m the number of samples // 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) Classifier& Classifier::fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states)
@@ -112,7 +112,7 @@ namespace bayesnet {
} }
return model.score(X, y); return model.score(X, y);
} }
vector<string> Classifier::show() vector<string> Classifier::show() const
{ {
return model.show(); return model.show();
} }
@@ -124,16 +124,16 @@ namespace bayesnet {
} }
model.addNode(className); model.addNode(className);
} }
int Classifier::getNumberOfNodes() int Classifier::getNumberOfNodes() const
{ {
// Features does not include class // Features does not include class
return fitted ? model.getFeatures().size() + 1 : 0; 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; return fitted ? model.getStates() : 0;
} }
@@ -141,7 +141,7 @@ namespace bayesnet {
{ {
return model.topological_sort(); return model.topological_sort();
} }
void Classifier::dump_cpt() void Classifier::dump_cpt() const
{ {
model.dump_cpt(); model.dump_cpt();
} }

View File

@@ -23,7 +23,7 @@ namespace bayesnet {
map<string, vector<int>> states; map<string, vector<int>> states;
void checkFitParameters(); void checkFitParameters();
virtual void buildModel() = 0; virtual void buildModel() = 0;
virtual void trainModel(); void trainModel() override;
public: public:
Classifier(Network model); Classifier(Network model);
virtual ~Classifier() = default; virtual ~Classifier() = default;
@@ -31,16 +31,16 @@ namespace bayesnet {
Classifier& fit(torch::Tensor& X, torch::Tensor& 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; Classifier& fit(torch::Tensor& dataset, vector<string>& features, string className, map<string, vector<int>>& states) override;
void addNodes(); void addNodes();
int getNumberOfNodes() override; int getNumberOfNodes() const override;
int getNumberOfEdges() override; int getNumberOfEdges() const override;
int getNumberOfStates() override; int getNumberOfStates() const override;
Tensor predict(Tensor& X) override; Tensor predict(Tensor& X) override;
vector<int> predict(vector<vector<int>>& X) override; vector<int> predict(vector<vector<int>>& X) override;
float score(Tensor& X, Tensor& y) override; float score(Tensor& X, Tensor& y) override;
float score(vector<vector<int>>& X, vector<int>& y) override; float score(vector<vector<int>>& X, vector<int>& y) override;
vector<string> show() override; vector<string> show() const override;
vector<string> topological_order() override; vector<string> topological_order() override;
void dump_cpt() override; void dump_cpt() const override;
}; };
} }
#endif #endif

View File

@@ -94,7 +94,7 @@ namespace bayesnet {
} }
return (double)correct / y_pred.size(); return (double)correct / y_pred.size();
} }
vector<string> Ensemble::show() vector<string> Ensemble::show() const
{ {
auto result = vector<string>(); auto result = vector<string>();
for (auto i = 0; i < n_models; ++i) { for (auto i = 0; i < n_models; ++i) {
@@ -103,7 +103,7 @@ namespace bayesnet {
} }
return result; return result;
} }
vector<string> Ensemble::graph(const string& title) vector<string> Ensemble::graph(const string& title) const
{ {
auto result = vector<string>(); auto result = vector<string>();
for (auto i = 0; i < n_models; ++i) { for (auto i = 0; i < n_models; ++i) {
@@ -112,7 +112,7 @@ namespace bayesnet {
} }
return result; return result;
} }
int Ensemble::getNumberOfNodes() int Ensemble::getNumberOfNodes() const
{ {
int nodes = 0; int nodes = 0;
for (auto i = 0; i < n_models; ++i) { for (auto i = 0; i < n_models; ++i) {
@@ -120,7 +120,7 @@ namespace bayesnet {
} }
return nodes; return nodes;
} }
int Ensemble::getNumberOfEdges() int Ensemble::getNumberOfEdges() const
{ {
int edges = 0; int edges = 0;
for (auto i = 0; i < n_models; ++i) { for (auto i = 0; i < n_models; ++i) {
@@ -128,7 +128,7 @@ namespace bayesnet {
} }
return edges; return edges;
} }
int Ensemble::getNumberOfStates() int Ensemble::getNumberOfStates() const
{ {
int nstates = 0; int nstates = 0;
for (auto i = 0; i < n_models; ++i) { for (auto i = 0; i < n_models; ++i) {

View File

@@ -23,16 +23,16 @@ namespace bayesnet {
vector<int> predict(vector<vector<int>>& X) override; vector<int> predict(vector<vector<int>>& X) override;
float score(Tensor& X, Tensor& y) override; float score(Tensor& X, Tensor& y) override;
float score(vector<vector<int>>& X, vector<int>& y) override; float score(vector<vector<int>>& X, vector<int>& y) override;
int getNumberOfNodes() override; int getNumberOfNodes() const override;
int getNumberOfEdges() override; int getNumberOfEdges() const override;
int getNumberOfStates() override; int getNumberOfStates() const override;
vector<string> show() override; vector<string> show() const override;
vector<string> graph(const string& title) override; vector<string> graph(const string& title) const override;
vector<string> topological_order() override vector<string> topological_order() override
{ {
return vector<string>(); return vector<string>();
} }
void dump_cpt() override void dump_cpt() const override
{ {
} }
}; };

View File

@@ -79,7 +79,7 @@ namespace bayesnet {
exit_cond = num == n_edges || candidates.size(0) == 0; 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 }; string header{ title };
if (title == "KDB") { if (title == "KDB") {

View File

@@ -15,7 +15,7 @@ namespace bayesnet {
public: public:
explicit KDB(int k, float theta = 0.03); explicit KDB(int k, float theta = 0.03);
virtual ~KDB() {}; virtual ~KDB() {};
vector<string> graph(const string& name = "KDB") override; vector<string> graph(const string& name = "KDB") const override;
}; };
} }
#endif #endif

View File

@@ -11,11 +11,11 @@ namespace bayesnet {
Xf = X_; Xf = X_;
y = y_; y = y_;
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & y // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
fit_local_discretization(states, y); states = fit_local_discretization(y);
// We have discretized the input data // 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 // 1st we need to fit the model to build the normal KDB structure, KDB::fit initializes the base Bayesian network
KDB::fit(dataset, features, className, states); KDB::fit(dataset, features, className, states);
localDiscretizationProposal(states, model); states = localDiscretizationProposal(states, model);
return *this; return *this;
} }
Tensor KDBLd::predict(Tensor& X) Tensor KDBLd::predict(Tensor& X)
@@ -23,7 +23,7 @@ namespace bayesnet {
auto Xt = prepareX(X); auto Xt = prepareX(X);
return KDB::predict(Xt); return KDB::predict(Xt);
} }
vector<string> KDBLd::graph(const string& name) vector<string> KDBLd::graph(const string& name) const
{ {
return KDB::graph(name); return KDB::graph(name);
} }

View File

@@ -11,7 +11,7 @@ namespace bayesnet {
explicit KDBLd(int k); explicit KDBLd(int k);
virtual ~KDBLd() = default; virtual ~KDBLd() = default;
KDBLd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override; 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; Tensor predict(Tensor& X) override;
static inline string version() { return "0.0.1"; }; static inline string version() { return "0.0.1"; };
}; };

View File

@@ -43,15 +43,15 @@ namespace bayesnet {
} }
nodes[name] = std::make_unique<Node>(name); nodes[name] = std::make_unique<Node>(name);
} }
vector<string> Network::getFeatures() vector<string> Network::getFeatures() const
{ {
return features; return features;
} }
int Network::getClassNumStates() int Network::getClassNumStates() const
{ {
return classNumStates; return classNumStates;
} }
int Network::getStates() int Network::getStates() const
{ {
int result = 0; int result = 0;
for (auto& node : nodes) { for (auto& node : nodes) {
@@ -59,7 +59,7 @@ namespace bayesnet {
} }
return result; return result;
} }
string Network::getClassName() string Network::getClassName() const
{ {
return className; return className;
} }
@@ -104,7 +104,7 @@ namespace bayesnet {
{ {
return nodes; 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) { 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) + ")"); throw invalid_argument("X and y must have the same number of samples in Network::fit (" + to_string(n_samples) + " != " + to_string(n_samples_y) + ")");
@@ -122,39 +122,42 @@ namespace bayesnet {
if (find(features.begin(), features.end(), feature) == features.end()) { if (find(features.begin(), features.end(), feature) == features.end()) {
throw invalid_argument("Feature " + feature + " not found in Network::features"); 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 // Set states to every Node in the network
for (int i = 0; i < features.size(); ++i) { 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(); classNumStates = nodes[className]->getNumStates();
} }
// X comes in nxm, where n is the number of features and m the number of samples // X comes in nxm, where n is the number of features and m the number of samples
void Network::fit(const torch::Tensor& X, const torch::Tensor& y, const vector<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; this->className = className;
Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1); Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1);
samples = torch::cat({ X , ytmp }, 0); samples = torch::cat({ X , ytmp }, 0);
for (int i = 0; i < featureNames.size(); ++i) { for (int i = 0; i < featureNames.size(); ++i) {
auto row_feature = X.index({ i, "..." }); auto row_feature = X.index({ i, "..." });
} }
completeFit(); completeFit(states);
} }
void Network::fit(const torch::Tensor& samples, const vector<string>& featureNames, const string& className) 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); checkFitData(samples.size(1), samples.size(0) - 1, samples.size(1), featureNames, className, states);
this->className = className; this->className = className;
this->samples = samples; this->samples = samples;
completeFit(); completeFit(states);
} }
// input_data comes in nxm, where n is the number of features and m the number of samples // 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; this->className = className;
// Build 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); samples = torch::zeros({ static_cast<int>(input_data.size() + 1), static_cast<int>(input_data[0].size()) }, torch::kInt32);
@@ -162,11 +165,11 @@ namespace bayesnet {
samples.index_put_({ i, "..." }, torch::tensor(input_data[i], torch::kInt32)); samples.index_put_({ i, "..." }, torch::tensor(input_data[i], torch::kInt32));
} }
samples.index_put_({ -1, "..." }, torch::tensor(labels, torch::kInt32)); 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); int maxThreadsRunning = static_cast<int>(std::thread::hardware_concurrency() * maxThreads);
if (maxThreadsRunning < 1) { if (maxThreadsRunning < 1) {
maxThreadsRunning = 1; maxThreadsRunning = 1;
@@ -212,7 +215,7 @@ namespace bayesnet {
torch::Tensor result; torch::Tensor result;
result = torch::zeros({ samples.size(1), classNumStates }, torch::kFloat64); result = torch::zeros({ samples.size(1), classNumStates }, torch::kFloat64);
for (int i = 0; i < samples.size(1); ++i) { 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 psample = predict_sample(sample);
auto temp = torch::tensor(psample, torch::kFloat64); auto temp = torch::tensor(psample, torch::kFloat64);
// result.index_put_({ i, "..." }, torch::tensor(predict_sample(sample), torch::kFloat64)); // result.index_put_({ i, "..." }, torch::tensor(predict_sample(sample), torch::kFloat64));
@@ -343,7 +346,7 @@ namespace bayesnet {
transform(result.begin(), result.end(), result.begin(), [sum](double& value) { return value / sum; }); transform(result.begin(), result.end(), result.begin(), [sum](double& value) { return value / sum; });
return result; return result;
} }
vector<string> Network::show() vector<string> Network::show() const
{ {
vector<string> result; vector<string> result;
// Draw the network // Draw the network
@@ -356,7 +359,7 @@ namespace bayesnet {
} }
return result; return result;
} }
vector<string> Network::graph(const string& title) vector<string> Network::graph(const string& title) const
{ {
auto output = vector<string>(); auto output = vector<string>();
auto prefix = "digraph BayesNet {\nlabel=<BayesNet "; auto prefix = "digraph BayesNet {\nlabel=<BayesNet ";
@@ -370,7 +373,7 @@ namespace bayesnet {
output.push_back("}\n"); output.push_back("}\n");
return output; return output;
} }
vector<pair<string, string>> Network::getEdges() vector<pair<string, string>> Network::getEdges() const
{ {
auto edges = vector<pair<string, string>>(); auto edges = vector<pair<string, string>>();
for (const auto& node : nodes) { for (const auto& node : nodes) {
@@ -382,6 +385,10 @@ namespace bayesnet {
} }
return edges; return edges;
} }
int Network::getNumEdges() const
{
return getEdges().size();
}
vector<string> Network::topological_sort() vector<string> Network::topological_sort()
{ {
/* Check if al the fathers of every node are before the node */ /* Check if al the fathers of every node are before the node */
@@ -420,7 +427,7 @@ namespace bayesnet {
} }
return result; return result;
} }
void Network::dump_cpt() void Network::dump_cpt() const
{ {
for (auto& node : nodes) { for (auto& node : nodes) {
cout << "* " << node.first << ": (" << node.second->getNumStates() << ") : " << node.second->getCPT().sizes() << endl; cout << "* " << node.first << ": (" << node.second->getNumStates() << ") : " << node.second->getCPT().sizes() << endl;

View File

@@ -20,13 +20,9 @@ namespace bayesnet {
vector<double> predict_sample(const torch::Tensor&); vector<double> predict_sample(const torch::Tensor&);
vector<double> exactInference(map<string, int>&); vector<double> exactInference(map<string, int>&);
double computeFactor(map<string, int>&); double computeFactor(map<string, int>&);
double mutual_info(torch::Tensor&, torch::Tensor&); void completeFit(const map<string, vector<int>>&);
double entropy(torch::Tensor&); void checkFitData(int n_features, int n_samples, int n_samples_y, const vector<string>& featureNames, const string& className, const map<string, vector<int>>&);
double conditionalEntropy(torch::Tensor&, torch::Tensor&); void setStates(const map<string, vector<int>>&);
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: public:
Network(); Network();
explicit Network(float, int); explicit Network(float, int);
@@ -37,27 +33,26 @@ namespace bayesnet {
void addNode(const string&); void addNode(const string&);
void addEdge(const string&, const string&); void addEdge(const string&, const string&);
map<string, std::unique_ptr<Node>>& getNodes(); map<string, std::unique_ptr<Node>>& getNodes();
vector<string> getFeatures(); vector<string> getFeatures() const;
int getStates(); int getStates() const;
vector<pair<string, string>> getEdges(); vector<pair<string, string>> getEdges() const;
int getClassNumStates(); int getNumEdges() const;
string getClassName(); int getClassNumStates() const;
void fit(const vector<vector<int>>&, const vector<int>&, const vector<string>&, const string&); string getClassName() const;
void fit(const torch::Tensor&, const torch::Tensor&, const vector<string>&, const string&); 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 vector<string>&, const string&); 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 vector<int> predict(const vector<vector<int>>&); // Return mx1 vector of predictions
torch::Tensor predict(const torch::Tensor&); // Return mx1 tensor 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); 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 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 torch::Tensor predict_proba(const torch::Tensor&); // Return mxn tensor of probabilities
double score(const vector<vector<int>>&, const vector<int>&); double score(const vector<vector<int>>&, const vector<int>&);
vector<string> topological_sort(); vector<string> topological_sort();
vector<string> show(); vector<string> show() const;
vector<string> graph(const string& title); // Returns a vector of strings representing the graph in graphviz format vector<string> graph(const string& title) const; // Returns a vector of strings representing the graph in graphviz format
void initialize(); void initialize();
void dump_cpt(); void dump_cpt() const;
inline string version() { return "0.1.0"; } inline string version() { return "0.1.0"; }
}; };
} }

View File

@@ -2,19 +2,20 @@
#include "ArffFiles.h" #include "ArffFiles.h"
namespace bayesnet { namespace bayesnet {
Proposal::Proposal(torch::Tensor& dataset_, vector<string>& features_, string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_), m(dataset_.size(1)), n(dataset_.size(0) - 1) {} Proposal::Proposal(torch::Tensor& dataset_, vector<string>& features_, string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_) {}
Proposal::~Proposal() Proposal::~Proposal()
{ {
for (auto& [key, value] : discretizers) { for (auto& [key, value] : discretizers) {
delete value; 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... // order of local discretization is important. no good 0, 1, 2...
// although we rediscretize features after the local discretization of every feature // although we rediscretize features after the local discretization of every feature
auto order = model.topological_sort(); auto order = model.topological_sort();
auto& nodes = model.getNodes(); auto& nodes = model.getNodes();
map<string, vector<int>> states = oldStates;
vector<int> indicesToReDiscretize; vector<int> indicesToReDiscretize;
bool upgrade = false; // Flag to check if we need to upgrade the model bool upgrade = false; // Flag to check if we need to upgrade the model
for (auto feature : order) { for (auto feature : order) {
@@ -32,9 +33,9 @@ namespace bayesnet {
indices.push_back(-1); // Add class index 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(); }); 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) // 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(indices.size()); vector<string> yJoinParents(Xf.size(1));
for (auto idx : indices) { for (auto idx : indices) {
for (int i = 0; i < n; ++i) { for (int i = 0; i < Xf.size(1); ++i) {
yJoinParents[i] += to_string(pDataset.index({ idx, i }).item<int>()); yJoinParents[i] += to_string(pDataset.index({ idx, i }).item<int>());
} }
} }
@@ -64,10 +65,16 @@ namespace bayesnet {
//Update new states of the feature/node //Update new states of the feature/node
states[pFeatures[index]] = xStates; 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)
{ {
// 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); pDataset = torch::zeros({ n + 1, m }, kInt32);
auto yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0)); auto yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
// discretize input data by feature(row) // discretize input data by feature(row)
@@ -86,6 +93,8 @@ namespace bayesnet {
auto yStates = vector<int>(n_classes); auto yStates = vector<int>(n_classes);
iota(yStates.begin(), yStates.end(), 0); iota(yStates.begin(), yStates.end(), 0);
states[pClassName] = yStates; states[pClassName] = yStates;
pDataset.index_put_({ n, "..." }, y);
return states;
} }
torch::Tensor Proposal::prepareX(torch::Tensor& X) torch::Tensor Proposal::prepareX(torch::Tensor& X)
{ {

View File

@@ -14,12 +14,11 @@ namespace bayesnet {
virtual ~Proposal(); virtual ~Proposal();
protected: protected:
torch::Tensor prepareX(torch::Tensor& X); torch::Tensor prepareX(torch::Tensor& X);
void localDiscretizationProposal(map<string, vector<int>>& states, Network& model); map<string, vector<int>> localDiscretizationProposal(const map<string, vector<int>>& states, Network& model);
void fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y); map<string, vector<int>> fit_local_discretization(const torch::Tensor& y);
torch::Tensor Xf; // X continuous nxm tensor torch::Tensor Xf; // X continuous nxm tensor
torch::Tensor y; // y discrete nx1 tensor torch::Tensor y; // y discrete nx1 tensor
map<string, mdlp::CPPFImdlp*> discretizers; map<string, mdlp::CPPFImdlp*> discretizers;
int m, n;
private: private:
torch::Tensor& pDataset; // (n+1)xm tensor torch::Tensor& pDataset; // (n+1)xm tensor
vector<string>& pFeatures; vector<string>& pFeatures;

View File

@@ -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); return model.graph(name);
} }

View File

@@ -11,7 +11,7 @@ namespace bayesnet {
public: public:
explicit SPODE(int root); explicit SPODE(int root);
virtual ~SPODE() {}; virtual ~SPODE() {};
vector<string> graph(const string& name = "SPODE") override; vector<string> graph(const string& name = "SPODE") const override;
}; };
} }
#endif #endif

View File

@@ -11,20 +11,36 @@ namespace bayesnet {
Xf = X_; Xf = X_;
y = y_; y = y_;
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & y // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
fit_local_discretization(states, y); states = fit_local_discretization(y);
// We have discretized the input data // 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 // 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); SPODE::fit(dataset, features, className, states);
localDiscretizationProposal(states, model); states = localDiscretizationProposal(states, model);
//model.fit(SPODE::Xv, SPODE::yv, features, className);
return *this; 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) Tensor SPODELd::predict(Tensor& X)
{ {
auto Xt = prepareX(X); auto Xt = prepareX(X);
return SPODE::predict(Xt); return SPODE::predict(Xt);
} }
vector<string> SPODELd::graph(const string& name) vector<string> SPODELd::graph(const string& name) const
{ {
return SPODE::graph(name); return SPODE::graph(name);
} }

View File

@@ -6,12 +6,12 @@
namespace bayesnet { namespace bayesnet {
using namespace std; using namespace std;
class SPODELd : public SPODE, public Proposal { class SPODELd : public SPODE, public Proposal {
private:
public: public:
explicit SPODELd(int root); explicit SPODELd(int root);
virtual ~SPODELd() = default; virtual ~SPODELd() = default;
SPODELd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override; 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; Tensor predict(Tensor& X) override;
static inline string version() { return "0.0.1"; }; static inline string version() { return "0.0.1"; };
}; };

View File

@@ -34,7 +34,7 @@ namespace bayesnet {
model.addEdge(className, feature); model.addEdge(className, feature);
} }
} }
vector<string> TAN::graph(const string& title) vector<string> TAN::graph(const string& title) const
{ {
return model.graph(title); return model.graph(title);
} }

View File

@@ -11,7 +11,7 @@ namespace bayesnet {
public: public:
TAN(); TAN();
virtual ~TAN() {}; virtual ~TAN() {};
vector<string> graph(const string& name = "TAN") override; vector<string> graph(const string& name = "TAN") const override;
}; };
} }
#endif #endif

View File

@@ -11,20 +11,20 @@ namespace bayesnet {
Xf = X_; Xf = X_;
y = y_; y = y_;
// Fills vectors Xv & yv with the data from tensors X_ (discretized) & y // Fills vectors Xv & yv with the data from tensors X_ (discretized) & y
fit_local_discretization(states, y); states = fit_local_discretization(y);
// We have discretized the input data // 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 // 1st we need to fit the model to build the normal TAN structure, TAN::fit initializes the base Bayesian network
TAN::fit(dataset, features, className, states); TAN::fit(dataset, features, className, states);
localDiscretizationProposal(states, model); states = localDiscretizationProposal(states, model);
//model.fit(dataset, features, className);
return *this; return *this;
} }
Tensor TANLd::predict(Tensor& X) Tensor TANLd::predict(Tensor& X)
{ {
auto Xt = prepareX(X); auto Xt = prepareX(X);
return TAN::predict(Xt); return TAN::predict(Xt);
} }
vector<string> TANLd::graph(const string& name) vector<string> TANLd::graph(const string& name) const
{ {
return TAN::graph(name); return TAN::graph(name);
} }

View File

@@ -11,7 +11,7 @@ namespace bayesnet {
TANLd(); TANLd();
virtual ~TANLd() = default; virtual ~TANLd() = default;
TANLd& fit(torch::Tensor& X, torch::Tensor& y, vector<string>& features, string className, map<string, vector<int>>& states) override; 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; Tensor predict(Tensor& X) override;
static inline string version() { return "0.0.1"; }; static inline string version() { return "0.0.1"; };
}; };

View File

@@ -4,6 +4,7 @@ namespace platform {
string headerLine(const string& text) string headerLine(const string& text)
{ {
int n = MAXL - text.length() - 3; int n = MAXL - text.length() - 3;
n = n < 0 ? 0 : n;
return "* " + text + string(n, ' ') + "*\n"; return "* " + text + string(n, ' ') + "*\n";
} }
string Report::fromVector(const string& key) string Report::fromVector(const string& key)
@@ -13,7 +14,7 @@ namespace platform {
for (auto& item : data[key]) { for (auto& item : data[key]) {
result += to_string(item) + ", "; result += to_string(item) + ", ";
} }
return "[" + result.substr(0, result.length() - 2) + "]"; return "[" + result.substr(0, result.size() - 2) + "]";
} }
string fVector(const json& data) string fVector(const json& data)
{ {
@@ -21,7 +22,7 @@ namespace platform {
for (const auto& item : data) { for (const auto& item : data) {
result += to_string(item) + ", "; result += to_string(item) + ", ";
} }
return "[" + result.substr(0, result.length() - 2) + "]"; return "[" + result.substr(0, result.size() - 2) + "]";
} }
void Report::show() void Report::show()
{ {