Refactor library and models to lighten data stored
Refactro Ensemble to inherit from Classifier insted of BaseClassifier
This commit is contained in:
parent
e74565ba01
commit
06db8f51ce
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
AODE::AODE() : Ensemble() {}
|
AODE::AODE() : Ensemble() {}
|
||||||
void AODE::train()
|
void AODE::buildModel()
|
||||||
{
|
{
|
||||||
models.clear();
|
models.clear();
|
||||||
for (int i = 0; i < features.size(); ++i) {
|
for (int i = 0; i < features.size(); ++i) {
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
class AODE : public Ensemble {
|
class AODE : public Ensemble {
|
||||||
protected:
|
protected:
|
||||||
void train() override;
|
void buildModel() override;
|
||||||
public:
|
public:
|
||||||
AODE();
|
AODE();
|
||||||
virtual ~AODE() {};
|
virtual ~AODE() {};
|
||||||
|
@ -2,27 +2,31 @@
|
|||||||
|
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
using namespace std;
|
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_)
|
AODELd& AODELd::fit(torch::Tensor& X_, torch::Tensor& y_, vector<string>& features_, string className_, map<string, vector<int>>& states_)
|
||||||
{
|
{
|
||||||
features = features_;
|
features = features_;
|
||||||
className = className_;
|
className = className_;
|
||||||
states = states_;
|
states = states_;
|
||||||
train();
|
buildModel();
|
||||||
for (const auto& model : models) {
|
trainModel();
|
||||||
model->fit(X_, y_, features_, className_, states_);
|
|
||||||
}
|
|
||||||
n_models = models.size();
|
n_models = models.size();
|
||||||
fitted = true;
|
fitted = true;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
void AODELd::train()
|
void AODELd::buildModel()
|
||||||
{
|
{
|
||||||
models.clear();
|
models.clear();
|
||||||
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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
void AODELd::trainModel()
|
||||||
|
{
|
||||||
|
for (const auto& model : models) {
|
||||||
|
model->fit(dataset, features, className, states);
|
||||||
|
}
|
||||||
|
}
|
||||||
Tensor AODELd::predict(Tensor& X)
|
Tensor AODELd::predict(Tensor& X)
|
||||||
{
|
{
|
||||||
return Ensemble::predict(X);
|
return Ensemble::predict(X);
|
||||||
|
@ -7,13 +7,15 @@
|
|||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
using namespace std;
|
using namespace std;
|
||||||
class AODELd : public Ensemble, public Proposal {
|
class AODELd : public Ensemble, public Proposal {
|
||||||
|
private:
|
||||||
|
void trainModel();
|
||||||
|
void buildModel() override;
|
||||||
public:
|
public:
|
||||||
AODELd();
|
AODELd();
|
||||||
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;
|
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;
|
vector<string> graph(const string& name = "AODE") override;
|
||||||
Tensor predict(Tensor& X) override;
|
Tensor predict(Tensor& X) override;
|
||||||
void train() override;
|
|
||||||
static inline string version() { return "0.0.1"; };
|
static inline string version() { return "0.0.1"; };
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -10,6 +10,7 @@ namespace bayesnet {
|
|||||||
virtual BaseClassifier& fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states) = 0;
|
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
|
// 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& 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;
|
virtual ~BaseClassifier() = default;
|
||||||
torch::Tensor virtual predict(torch::Tensor& X) = 0;
|
torch::Tensor virtual predict(torch::Tensor& X) = 0;
|
||||||
vector<int> virtual predict(vector<vector<int>>& X) = 0;
|
vector<int> virtual predict(vector<vector<int>>& X) = 0;
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
#include "Mst.h"
|
#include "Mst.h"
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
//samples is nxm tensor used to fit the model
|
//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)
|
: samples(samples)
|
||||||
, features(features)
|
, features(features)
|
||||||
, className(className)
|
, className(className)
|
||||||
@ -76,7 +76,7 @@ namespace bayesnet {
|
|||||||
std::vector<float> v(matrix.data_ptr<float>(), matrix.data_ptr<float>() + matrix.numel());
|
std::vector<float> v(matrix.data_ptr<float>(), matrix.data_ptr<float>() + matrix.numel());
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
double Metrics::entropy(torch::Tensor& feature)
|
double Metrics::entropy(const torch::Tensor& feature)
|
||||||
{
|
{
|
||||||
torch::Tensor counts = feature.bincount();
|
torch::Tensor counts = feature.bincount();
|
||||||
int totalWeight = counts.sum().item<int>();
|
int totalWeight = counts.sum().item<int>();
|
||||||
@ -86,7 +86,7 @@ namespace bayesnet {
|
|||||||
return entropy.nansum().item<double>();
|
return entropy.nansum().item<double>();
|
||||||
}
|
}
|
||||||
// H(Y|X) = sum_{x in X} p(x) H(Y|X=x)
|
// 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];
|
int numSamples = firstFeature.sizes()[0];
|
||||||
torch::Tensor featureCounts = secondFeature.bincount();
|
torch::Tensor featureCounts = secondFeature.bincount();
|
||||||
@ -115,7 +115,7 @@ namespace bayesnet {
|
|||||||
return entropyValue;
|
return entropyValue;
|
||||||
}
|
}
|
||||||
// I(X;Y) = H(Y) - H(Y|X)
|
// 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);
|
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
|
and the indices of the weights as nodes of this square matrix using
|
||||||
Kruskal algorithm
|
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);
|
auto mst = MST(features, weights, root);
|
||||||
return mst.maximumSpanningTree();
|
return mst.maximumSpanningTree();
|
||||||
|
@ -14,15 +14,15 @@ namespace bayesnet {
|
|||||||
int classNumStates = 0;
|
int classNumStates = 0;
|
||||||
public:
|
public:
|
||||||
Metrics() = default;
|
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);
|
Metrics(const vector<vector<int>>&, const vector<int>&, const vector<string>&, const string&, const int);
|
||||||
double entropy(Tensor&);
|
double entropy(const Tensor&);
|
||||||
double conditionalEntropy(Tensor&, Tensor&);
|
double conditionalEntropy(const Tensor&, const Tensor&);
|
||||||
double mutualInformation(Tensor&, Tensor&);
|
double mutualInformation(const Tensor&, const Tensor&);
|
||||||
vector<float> conditionalEdgeWeights(); // To use in Python
|
vector<float> conditionalEdgeWeights(); // To use in Python
|
||||||
Tensor conditionalEdge();
|
Tensor conditionalEdge();
|
||||||
vector<pair<string, string>> doCombinations(const vector<string>&);
|
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
|
#endif
|
@ -7,59 +7,54 @@ namespace bayesnet {
|
|||||||
Classifier::Classifier(Network model) : model(model), m(0), n(0), metrics(Metrics()), fitted(false) {}
|
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)
|
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->features = features;
|
||||||
this->className = className;
|
this->className = className;
|
||||||
this->states = states;
|
this->states = states;
|
||||||
checkFitParameters();
|
checkFitParameters();
|
||||||
auto n_classes = states[className].size();
|
auto n_classes = states[className].size();
|
||||||
metrics = Metrics(samples, features, className, n_classes);
|
metrics = Metrics(dataset, features, className, n_classes);
|
||||||
model.initialize();
|
model.initialize();
|
||||||
train();
|
buildModel();
|
||||||
if (Xv.empty()) {
|
m = dataset.size(1);
|
||||||
// fit with tensors
|
n = dataset.size(0);
|
||||||
model.fit(X, y, features, className);
|
trainModel();
|
||||||
} else {
|
|
||||||
// fit with vectors
|
|
||||||
model.fit(Xv, yv, features, className);
|
|
||||||
}
|
|
||||||
fitted = true;
|
fitted = true;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
void Classifier::trainModel()
|
||||||
|
{
|
||||||
|
model.fit(dataset, features, className);
|
||||||
|
}
|
||||||
|
void Classifier::buildDataset(Tensor& ytmp)
|
||||||
|
{
|
||||||
|
ytmp = torch::transpose(ytmp.view({ ytmp.size(0), 1 }), 0, 1);
|
||||||
|
dataset = torch::cat({ dataset, ytmp }, 0);
|
||||||
|
}
|
||||||
// X is nxm where n is the number of features and m the number of samples
|
// 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)
|
||||||
{
|
{
|
||||||
this->X = X;
|
dataset = X;
|
||||||
this->y = y;
|
buildDataset(y);
|
||||||
Xv = vector<vector<int>>();
|
|
||||||
yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
|
||||||
return build(features, className, states);
|
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
|
// 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)
|
Classifier& Classifier::fit(vector<vector<int>>& X, vector<int>& y, vector<string>& features, string className, map<string, vector<int>>& states)
|
||||||
{
|
{
|
||||||
Xv = X;
|
dataset = torch::zeros({ static_cast<int>(X.size()), static_cast<int>(X[0].size()) }, kInt32);
|
||||||
generateTensorXFromVector();
|
for (int i = 0; i < X.size(); ++i) {
|
||||||
this->y = torch::tensor(y, kInt32);
|
dataset.index_put_({ i, "..." }, torch::tensor(X[i], kInt32));
|
||||||
yv = y;
|
}
|
||||||
|
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);
|
return build(features, className, states);
|
||||||
}
|
}
|
||||||
void Classifier::checkFitParameters()
|
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()) {
|
if (n != features.size()) {
|
||||||
throw invalid_argument("X and features must have the same number of features");
|
throw invalid_argument("X and features must have the same number of features");
|
||||||
}
|
}
|
||||||
@ -141,5 +136,4 @@ namespace bayesnet {
|
|||||||
{
|
{
|
||||||
model.dump_cpt();
|
model.dump_cpt();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -10,28 +10,26 @@ using namespace torch;
|
|||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
class Classifier : public BaseClassifier {
|
class Classifier : public BaseClassifier {
|
||||||
private:
|
private:
|
||||||
bool fitted;
|
void buildDataset(torch::Tensor& y);
|
||||||
Classifier& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
Classifier& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
||||||
protected:
|
protected:
|
||||||
|
bool fitted;
|
||||||
Network model;
|
Network model;
|
||||||
int m, n; // m: number of samples, n: number of features
|
int m, n; // m: number of samples, n: number of features
|
||||||
Tensor X; // nxm tensor
|
Tensor dataset; // (n+1)xm tensor
|
||||||
vector<vector<int>> Xv; // nxm vector
|
|
||||||
Tensor y;
|
|
||||||
vector<int> yv;
|
|
||||||
Tensor samples; // (n+1)xm tensor
|
|
||||||
Metrics metrics;
|
Metrics metrics;
|
||||||
vector<string> features;
|
vector<string> features;
|
||||||
string className;
|
string className;
|
||||||
map<string, vector<int>> states;
|
map<string, vector<int>> states;
|
||||||
void checkFitParameters();
|
void checkFitParameters();
|
||||||
void generateTensorXFromVector();
|
virtual void buildModel() = 0;
|
||||||
virtual void train() = 0;
|
void trainModel();
|
||||||
public:
|
public:
|
||||||
Classifier(Network model);
|
Classifier(Network model);
|
||||||
virtual ~Classifier() = default;
|
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(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& 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();
|
void addNodes();
|
||||||
int getNumberOfNodes() override;
|
int getNumberOfNodes() override;
|
||||||
int getNumberOfEdges() override;
|
int getNumberOfEdges() override;
|
||||||
|
@ -3,54 +3,15 @@
|
|||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
using namespace torch;
|
using namespace torch;
|
||||||
|
|
||||||
Ensemble::Ensemble() : n_models(0), metrics(Metrics()), fitted(false) {}
|
Ensemble::Ensemble() : Classifier(Network()) {}
|
||||||
Ensemble& Ensemble::build(vector<string>& features, string className, map<string, vector<int>>& states)
|
|
||||||
|
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();
|
n_models = models.size();
|
||||||
for (auto i = 0; i < n_models; ++i) {
|
for (auto i = 0; i < n_models; ++i) {
|
||||||
if (Xv.empty()) {
|
// fit with vectors
|
||||||
// fit with tensors
|
models[i]->fit(dataset, features, className, states);
|
||||||
models[i]->fit(X, y, features, className, states);
|
|
||||||
} else {
|
|
||||||
// fit with vectors
|
|
||||||
models[i]->fit(Xv, yv, 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)
|
vector<int> Ensemble::voting(Tensor& y_pred)
|
||||||
{
|
{
|
||||||
@ -132,7 +93,6 @@ namespace bayesnet {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return (double)correct / y_pred.size();
|
return (double)correct / y_pred.size();
|
||||||
|
|
||||||
}
|
}
|
||||||
vector<string> Ensemble::show()
|
vector<string> Ensemble::show()
|
||||||
{
|
{
|
||||||
|
@ -8,30 +8,17 @@ using namespace std;
|
|||||||
using namespace torch;
|
using namespace torch;
|
||||||
|
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
class Ensemble : public BaseClassifier {
|
class Ensemble : public Classifier {
|
||||||
private:
|
private:
|
||||||
Ensemble& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
Ensemble& build(vector<string>& features, string className, map<string, vector<int>>& states);
|
||||||
protected:
|
protected:
|
||||||
unsigned n_models;
|
unsigned n_models;
|
||||||
bool fitted;
|
|
||||||
vector<unique_ptr<Classifier>> models;
|
vector<unique_ptr<Classifier>> models;
|
||||||
Tensor X;
|
void trainModel();
|
||||||
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;
|
|
||||||
vector<int> voting(Tensor& y_pred);
|
vector<int> voting(Tensor& y_pred);
|
||||||
void generateTensorXFromVector();
|
|
||||||
public:
|
public:
|
||||||
Ensemble();
|
Ensemble();
|
||||||
virtual ~Ensemble() = default;
|
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;
|
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;
|
||||||
|
@ -4,7 +4,7 @@ namespace bayesnet {
|
|||||||
using namespace torch;
|
using namespace torch;
|
||||||
|
|
||||||
KDB::KDB(int k, float theta) : Classifier(Network()), k(k), theta(theta) {}
|
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),
|
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),
|
// 1. For each feature Xi, compute mutual information, I(X;C),
|
||||||
// where C is the class.
|
// where C is the class.
|
||||||
addNodes();
|
addNodes();
|
||||||
|
const Tensor& y = dataset.index({ -1, "..." });
|
||||||
vector <float> mi;
|
vector <float> mi;
|
||||||
for (auto i = 0; i < features.size(); i++) {
|
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));
|
mi.push_back(metrics.mutualInformation(firstFeature, y));
|
||||||
}
|
}
|
||||||
// 2. Compute class conditional mutual information I(Xi;XjIC), f or each
|
// 2. Compute class conditional mutual information I(Xi;XjIC), f or each
|
||||||
|
@ -11,7 +11,7 @@ namespace bayesnet {
|
|||||||
float theta;
|
float theta;
|
||||||
void add_m_edges(int idx, vector<int>& S, Tensor& weights);
|
void add_m_edges(int idx, vector<int>& S, Tensor& weights);
|
||||||
protected:
|
protected:
|
||||||
void train() override;
|
void buildModel() override;
|
||||||
public:
|
public:
|
||||||
explicit KDB(int k, float theta = 0.03);
|
explicit KDB(int k, float theta = 0.03);
|
||||||
virtual ~KDB() {};
|
virtual ~KDB() {};
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
using namespace std;
|
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_)
|
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...
|
// This first part should go in a Classifier method called fit_local_discretization o fit_float...
|
||||||
@ -12,15 +12,10 @@ namespace bayesnet {
|
|||||||
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);
|
fit_local_discretization(states, y);
|
||||||
generateTensorXFromVector();
|
|
||||||
// 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(KDB::Xv, KDB::yv, features, className, states);
|
KDB::fit(dataset, features, className, states);
|
||||||
localDiscretizationProposal(states, model);
|
localDiscretizationProposal(states, model);
|
||||||
generateTensorXFromVector();
|
|
||||||
Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1);
|
|
||||||
samples = torch::cat({ X, ytmp }, 0);
|
|
||||||
model.fit(KDB::Xv, KDB::yv, features, className);
|
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
Tensor KDBLd::predict(Tensor& X)
|
Tensor KDBLd::predict(Tensor& X)
|
||||||
|
@ -94,7 +94,7 @@ namespace bayesnet {
|
|||||||
return result;
|
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()
|
vector<pair<int, int>> MST::maximumSpanningTree()
|
||||||
{
|
{
|
||||||
auto num_features = features.size();
|
auto num_features = features.size();
|
||||||
|
@ -13,7 +13,7 @@ namespace bayesnet {
|
|||||||
int root = 0;
|
int root = 0;
|
||||||
public:
|
public:
|
||||||
MST() = default;
|
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();
|
vector<pair<int, int>> maximumSpanningTree();
|
||||||
};
|
};
|
||||||
class Graph {
|
class Graph {
|
||||||
|
@ -20,7 +20,6 @@ namespace bayesnet {
|
|||||||
classNumStates = 0;
|
classNumStates = 0;
|
||||||
fitted = false;
|
fitted = false;
|
||||||
nodes.clear();
|
nodes.clear();
|
||||||
dataset.clear();
|
|
||||||
samples = torch::Tensor();
|
samples = torch::Tensor();
|
||||||
}
|
}
|
||||||
float Network::getmaxThreads()
|
float Network::getmaxThreads()
|
||||||
@ -134,18 +133,22 @@ namespace bayesnet {
|
|||||||
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(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)
|
||||||
{
|
{
|
||||||
checkFitData(X.size(1), X.size(0), y.size(0), featureNames, className);
|
checkFitData(X.size(1), X.size(0), y.size(0), featureNames, className);
|
||||||
this->className = className;
|
this->className = className;
|
||||||
dataset.clear();
|
|
||||||
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, "..." });
|
||||||
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();
|
||||||
|
}
|
||||||
|
void Network::fit(const torch::Tensor& samples, const vector<string>& featureNames, const string& className)
|
||||||
|
{
|
||||||
|
checkFitData(samples.size(1), samples.size(0) - 1, samples.size(1), featureNames, className);
|
||||||
|
this->className = className;
|
||||||
|
this->samples = samples;
|
||||||
completeFit();
|
completeFit();
|
||||||
}
|
}
|
||||||
// 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
|
||||||
@ -153,14 +156,11 @@ namespace bayesnet {
|
|||||||
{
|
{
|
||||||
checkFitData(input_data[0].size(), input_data.size(), labels.size(), featureNames, className);
|
checkFitData(input_data[0].size(), input_data.size(), labels.size(), featureNames, className);
|
||||||
this->className = className;
|
this->className = className;
|
||||||
dataset.clear();
|
// Build tensor of samples (nxm) (n+1 because of the class)
|
||||||
// Build dataset & tensor of samples (nxm) (n+1 because of the class)
|
|
||||||
samples = torch::zeros({ static_cast<int>(input_data.size() + 1), static_cast<int>(input_data[0].size()) }, torch::kInt32);
|
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) {
|
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));
|
samples.index_put_({ i, "..." }, torch::tensor(input_data[i], torch::kInt32));
|
||||||
}
|
}
|
||||||
dataset[className] = labels;
|
|
||||||
samples.index_put_({ -1, "..." }, torch::tensor(labels, torch::kInt32));
|
samples.index_put_({ -1, "..." }, torch::tensor(labels, torch::kInt32));
|
||||||
completeFit();
|
completeFit();
|
||||||
}
|
}
|
||||||
@ -188,7 +188,7 @@ namespace bayesnet {
|
|||||||
auto& pair = *std::next(nodes.begin(), nextNodeIndex);
|
auto& pair = *std::next(nodes.begin(), nextNodeIndex);
|
||||||
++nextNodeIndex;
|
++nextNodeIndex;
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
pair.second->computeCPT(dataset, laplaceSmoothing);
|
pair.second->computeCPT(samples, features, laplaceSmoothing);
|
||||||
lock.lock();
|
lock.lock();
|
||||||
nodes[pair.first] = std::move(pair.second);
|
nodes[pair.first] = std::move(pair.second);
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
@ -328,12 +328,12 @@ namespace bayesnet {
|
|||||||
mutex mtx;
|
mutex mtx;
|
||||||
for (int i = 0; i < classNumStates; ++i) {
|
for (int i = 0; i < classNumStates; ++i) {
|
||||||
threads.emplace_back([this, &result, &evidence, i, &mtx]() {
|
threads.emplace_back([this, &result, &evidence, i, &mtx]() {
|
||||||
auto completeEvidence = map<string, int>(evidence);
|
auto completeEvidence = map<string, int>(evidence);
|
||||||
completeEvidence[getClassName()] = i;
|
completeEvidence[getClassName()] = i;
|
||||||
double factor = computeFactor(completeEvidence);
|
double factor = computeFactor(completeEvidence);
|
||||||
lock_guard<mutex> lock(mtx);
|
lock_guard<mutex> lock(mtx);
|
||||||
result[i] = factor;
|
result[i] = factor;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
for (auto& thread : threads) {
|
for (auto& thread : threads) {
|
||||||
thread.join();
|
thread.join();
|
||||||
|
@ -8,11 +8,10 @@ namespace bayesnet {
|
|||||||
class Network {
|
class Network {
|
||||||
private:
|
private:
|
||||||
map<string, unique_ptr<Node>> nodes;
|
map<string, unique_ptr<Node>> nodes;
|
||||||
map<string, vector<int>> dataset;
|
|
||||||
bool fitted;
|
bool fitted;
|
||||||
float maxThreads = 0.95;
|
float maxThreads = 0.95;
|
||||||
int classNumStates;
|
int classNumStates;
|
||||||
vector<string> features; // Including class
|
vector<string> features; // Including classname
|
||||||
string className;
|
string className;
|
||||||
int laplaceSmoothing = 1;
|
int laplaceSmoothing = 1;
|
||||||
torch::Tensor samples; // nxm tensor used to fit the model
|
torch::Tensor samples; // nxm tensor used to fit the model
|
||||||
@ -44,7 +43,8 @@ namespace bayesnet {
|
|||||||
int getClassNumStates();
|
int getClassNumStates();
|
||||||
string getClassName();
|
string getClassName();
|
||||||
void fit(const vector<vector<int>>&, const vector<int>&, const vector<string>&, const string&);
|
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&);
|
void fit(const torch::Tensor&, const torch::Tensor&, const vector<string>&, const string&);
|
||||||
|
void fit(const torch::Tensor&, const vector<string>&, const string&);
|
||||||
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
|
//Computes the conditional edge weight of variable index u and v conditioned on class_node
|
||||||
|
@ -84,7 +84,7 @@ namespace bayesnet {
|
|||||||
}
|
}
|
||||||
return result;
|
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();
|
dimensions.clear();
|
||||||
// Get dimensions of the CPT
|
// Get dimensions of the CPT
|
||||||
@ -94,10 +94,22 @@ namespace bayesnet {
|
|||||||
// Create a tensor of zeros with the dimensions of the CPT
|
// Create a tensor of zeros with the dimensions of the CPT
|
||||||
cpTable = torch::zeros(dimensions, torch::kFloat) + laplaceSmoothing;
|
cpTable = torch::zeros(dimensions, torch::kFloat) + laplaceSmoothing;
|
||||||
// Fill table with counts
|
// 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;
|
torch::List<c10::optional<torch::Tensor>> coordinates;
|
||||||
coordinates.push_back(torch::tensor(dataset[name][n_sample]));
|
coordinates.push_back(dataset.index({ name_index, n_sample }));
|
||||||
transform(parents.begin(), parents.end(), back_inserter(coordinates), [&dataset, &n_sample](const auto& parent) { return torch::tensor(dataset[parent->getName()][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
|
// Increment the count of the corresponding coordinate
|
||||||
cpTable.index_put_({ coordinates }, cpTable.index({ coordinates }) + 1);
|
cpTable.index_put_({ coordinates }, cpTable.index({ coordinates }) + 1);
|
||||||
}
|
}
|
||||||
|
@ -26,7 +26,7 @@ namespace bayesnet {
|
|||||||
vector<Node*>& getParents();
|
vector<Node*>& getParents();
|
||||||
vector<Node*>& getChildren();
|
vector<Node*>& getChildren();
|
||||||
torch::Tensor& getCPT();
|
torch::Tensor& getCPT();
|
||||||
void computeCPT(map<string, vector<int>>&, const int);
|
void computeCPT(const torch::Tensor&, const vector<string>&, const int);
|
||||||
int getNumStates() const;
|
int getNumStates() const;
|
||||||
void setNumStates(int);
|
void setNumStates(int);
|
||||||
unsigned minFill();
|
unsigned minFill();
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
#include "ArffFiles.h"
|
#include "ArffFiles.h"
|
||||||
|
|
||||||
namespace bayesnet {
|
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_), m(dataset_.size(1)), n(dataset_.size(0) - 1) {}
|
||||||
Proposal::~Proposal()
|
Proposal::~Proposal()
|
||||||
{
|
{
|
||||||
for (auto& [key, value] : discretizers) {
|
for (auto& [key, value] : discretizers) {
|
||||||
@ -16,7 +16,6 @@ namespace bayesnet {
|
|||||||
auto order = model.topological_sort();
|
auto order = model.topological_sort();
|
||||||
auto& nodes = model.getNodes();
|
auto& nodes = model.getNodes();
|
||||||
vector<int> indicesToReDiscretize;
|
vector<int> indicesToReDiscretize;
|
||||||
auto n_samples = Xf.size(1);
|
|
||||||
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) {
|
||||||
auto nodeParents = nodes[feature]->getParents();
|
auto nodeParents = nodes[feature]->getParents();
|
||||||
@ -30,13 +29,13 @@ namespace bayesnet {
|
|||||||
parents.erase(remove(parents.begin(), parents.end(), pClassName), parents.end());
|
parents.erase(remove(parents.begin(), parents.end(), pClassName), parents.end());
|
||||||
// Get the indices of the parents
|
// Get the indices of the parents
|
||||||
vector<int> indices;
|
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(); });
|
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;
|
vector<string> yJoinParents(indices.size());
|
||||||
transform(yv.begin(), yv.end(), back_inserter(yJoinParents), [&](const auto& p) {return to_string(p); });
|
|
||||||
for (auto idx : indices) {
|
for (auto idx : indices) {
|
||||||
for (int i = 0; i < n_samples; ++i) {
|
for (int i = 0; i < n; ++i) {
|
||||||
yJoinParents[i] += to_string(Xv[idx][i]);
|
yJoinParents[i] += to_string(pDataset.index({ idx, i }).item<int>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
auto arff = ArffFiles();
|
auto arff = ArffFiles();
|
||||||
@ -59,7 +58,7 @@ namespace bayesnet {
|
|||||||
for (auto index : indicesToReDiscretize) {
|
for (auto index : indicesToReDiscretize) {
|
||||||
auto Xt_ptr = Xf.index({ index }).data_ptr<float>();
|
auto Xt_ptr = Xf.index({ index }).data_ptr<float>();
|
||||||
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
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);
|
auto xStates = vector<int>(discretizers[pFeatures[index]]->getCutPoints().size() + 1);
|
||||||
iota(xStates.begin(), xStates.end(), 0);
|
iota(xStates.begin(), xStates.end(), 0);
|
||||||
//Update new states of the feature/node
|
//Update new states of the feature/node
|
||||||
@ -69,16 +68,15 @@ namespace bayesnet {
|
|||||||
}
|
}
|
||||||
void Proposal::fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y)
|
void Proposal::fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y)
|
||||||
{
|
{
|
||||||
// Sharing Xv and yv with Classifier
|
pDataset = torch::zeros({ n + 1, m }, kInt32);
|
||||||
Xv = vector<vector<int>>();
|
auto yv = vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
|
||||||
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)
|
||||||
for (int i = 0; i < pFeatures.size(); ++i) {
|
for (auto i = 0; i < pFeatures.size(); ++i) {
|
||||||
auto* discretizer = new mdlp::CPPFImdlp();
|
auto* discretizer = new mdlp::CPPFImdlp();
|
||||||
auto Xt_ptr = Xf.index({ i }).data_ptr<float>();
|
auto Xt_ptr = Xf.index({ i }).data_ptr<float>();
|
||||||
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
auto Xt = vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
|
||||||
discretizer->fit(Xt, yv);
|
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);
|
auto xStates = vector<int>(discretizer->getCutPoints().size() + 1);
|
||||||
iota(xStates.begin(), xStates.end(), 0);
|
iota(xStates.begin(), xStates.end(), 0);
|
||||||
states[pFeatures[i]] = xStates;
|
states[pFeatures[i]] = xStates;
|
||||||
|
@ -10,19 +10,20 @@
|
|||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
class Proposal {
|
class Proposal {
|
||||||
public:
|
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();
|
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);
|
void localDiscretizationProposal(map<string, vector<int>>& states, Network& model);
|
||||||
void fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y);
|
void fit_local_discretization(map<string, vector<int>>& states, torch::Tensor& y);
|
||||||
torch::Tensor Xf; // X continuous nxm tensor
|
torch::Tensor Xf; // X continuous nxm 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
|
||||||
vector<string>& pFeatures;
|
vector<string>& pFeatures;
|
||||||
string& pClassName;
|
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) {}
|
SPODE::SPODE(int root) : Classifier(Network()), root(root) {}
|
||||||
|
|
||||||
void SPODE::train()
|
void SPODE::buildModel()
|
||||||
{
|
{
|
||||||
// 0. Add all nodes to the model
|
// 0. Add all nodes to the model
|
||||||
addNodes();
|
addNodes();
|
||||||
|
@ -7,7 +7,7 @@ namespace bayesnet {
|
|||||||
private:
|
private:
|
||||||
int root;
|
int root;
|
||||||
protected:
|
protected:
|
||||||
void train() override;
|
void buildModel() override;
|
||||||
public:
|
public:
|
||||||
explicit SPODE(int root);
|
explicit SPODE(int root);
|
||||||
virtual ~SPODE() {};
|
virtual ~SPODE() {};
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
using namespace std;
|
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_)
|
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...
|
// This first part should go in a Classifier method called fit_local_discretization o fit_float...
|
||||||
@ -12,15 +12,11 @@ namespace bayesnet {
|
|||||||
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);
|
fit_local_discretization(states, y);
|
||||||
generateTensorXFromVector();
|
|
||||||
// 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(SPODE::Xv, SPODE::yv, features, className, states);
|
SPODE::fit(dataset, features, className, states);
|
||||||
localDiscretizationProposal(states, model);
|
localDiscretizationProposal(states, model);
|
||||||
generateTensorXFromVector();
|
//model.fit(SPODE::Xv, SPODE::yv, features, className);
|
||||||
Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1);
|
|
||||||
samples = torch::cat({ X, ytmp }, 0);
|
|
||||||
model.fit(SPODE::Xv, SPODE::yv, features, className);
|
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
Tensor SPODELd::predict(Tensor& X)
|
Tensor SPODELd::predict(Tensor& X)
|
||||||
|
@ -5,16 +5,16 @@ namespace bayesnet {
|
|||||||
|
|
||||||
TAN::TAN() : Classifier(Network()) {}
|
TAN::TAN() : Classifier(Network()) {}
|
||||||
|
|
||||||
void TAN::train()
|
void TAN::buildModel()
|
||||||
{
|
{
|
||||||
// 0. Add all nodes to the model
|
// 0. Add all nodes to the model
|
||||||
addNodes();
|
addNodes();
|
||||||
// 1. Compute mutual information between each feature and the class and set the root node
|
// 1. Compute mutual information between each feature and the class and set the root node
|
||||||
// as the highest mutual information with the class
|
// as the highest mutual information with the class
|
||||||
auto mi = vector <pair<int, float >>();
|
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) {
|
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);
|
auto mi_value = metrics.mutualInformation(class_dataset, feature_dataset);
|
||||||
mi.push_back({ i, mi_value });
|
mi.push_back({ i, mi_value });
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ namespace bayesnet {
|
|||||||
class TAN : public Classifier {
|
class TAN : public Classifier {
|
||||||
private:
|
private:
|
||||||
protected:
|
protected:
|
||||||
void train() override;
|
void buildModel() override;
|
||||||
public:
|
public:
|
||||||
TAN();
|
TAN();
|
||||||
virtual ~TAN() {};
|
virtual ~TAN() {};
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace bayesnet {
|
namespace bayesnet {
|
||||||
using namespace std;
|
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_)
|
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...
|
// This first part should go in a Classifier method called fit_local_discretization o fit_float...
|
||||||
@ -12,15 +12,11 @@ namespace bayesnet {
|
|||||||
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);
|
fit_local_discretization(states, y);
|
||||||
generateTensorXFromVector();
|
|
||||||
// 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(TAN::Xv, TAN::yv, features, className, states);
|
TAN::fit(dataset, features, className, states);
|
||||||
localDiscretizationProposal(states, model);
|
localDiscretizationProposal(states, model);
|
||||||
generateTensorXFromVector();
|
//model.fit(dataset, features, className);
|
||||||
Tensor ytmp = torch::transpose(y.view({ y.size(0), 1 }), 0, 1);
|
|
||||||
samples = torch::cat({ X, ytmp }, 0);
|
|
||||||
model.fit(TAN::Xv, TAN::yv, features, className);
|
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
Tensor TANLd::predict(Tensor& X)
|
Tensor TANLd::predict(Tensor& X)
|
||||||
|
Loading…
Reference in New Issue
Block a user