Files
BayesNet/html/bayesnet/classifiers/Proposal.cc.gcov.html

20 KiB

<html lang="en"> <head> </head>
LCOV - code coverage report
Current view: top level - bayesnet/classifiers - Proposal.cc (source / functions) Coverage Total Hit
Test: coverage.info Lines: 97.7 % 86 84
Test Date: 2024-04-21 16:43:29 Functions: 88.9 % 9 8

            Line data    Source code
       1              : // ***************************************************************
       2              : // SPDX-FileCopyrightText: Copyright 2024 Ricardo Montañana Gómez
       3              : // SPDX-FileType: SOURCE
       4              : // SPDX-License-Identifier: MIT
       5              : // ***************************************************************
       6              : 
       7              : #include <ArffFiles.h>
       8              : #include "Proposal.h"
       9              : 
      10              : namespace bayesnet {
      11          106 :     Proposal::Proposal(torch::Tensor& dataset_, std::vector<std::string>& features_, std::string& className_) : pDataset(dataset_), pFeatures(features_), pClassName(className_) {}
      12           50 :     Proposal::~Proposal()
      13              :     {
      14          474 :         for (auto& [key, value] : discretizers) {
      15          424 :             delete value;
      16              :         }
      17           50 :     }
      18           57 :     void Proposal::checkInput(const torch::Tensor& X, const torch::Tensor& y)
      19              :     {
      20           57 :         if (!torch::is_floating_point(X)) {
      21            0 :             throw std::invalid_argument("X must be a floating point tensor");
      22              :         }
      23           57 :         if (torch::is_floating_point(y)) {
      24            0 :             throw std::invalid_argument("y must be an integer tensor");
      25              :         }
      26           57 :     }
      27           53 :     map<std::string, std::vector<int>> Proposal::localDiscretizationProposal(const map<std::string, std::vector<int>>& oldStates, Network& model)
      28              :     {
      29              :         // order of local discretization is important. no good 0, 1, 2...
      30              :         // although we rediscretize features after the local discretization of every feature
      31           53 :         auto order = model.topological_sort();
      32           53 :         auto& nodes = model.getNodes();
      33           53 :         map<std::string, std::vector<int>> states = oldStates;
      34           53 :         std::vector<int> indicesToReDiscretize;
      35           53 :         bool upgrade = false; // Flag to check if we need to upgrade the model
      36          444 :         for (auto feature : order) {
      37          391 :             auto nodeParents = nodes[feature]->getParents();
      38          391 :             if (nodeParents.size() < 2) continue; // Only has class as parent
      39          331 :             upgrade = true;
      40          331 :             int index = find(pFeatures.begin(), pFeatures.end(), feature) - pFeatures.begin();
      41          331 :             indicesToReDiscretize.push_back(index); // We need to re-discretize this feature
      42          331 :             std::vector<std::string> parents;
      43         1005 :             transform(nodeParents.begin(), nodeParents.end(), back_inserter(parents), [](const auto& p) { return p->getName(); });
      44              :             // Remove class as parent as it will be added later
      45          331 :             parents.erase(remove(parents.begin(), parents.end(), pClassName), parents.end());
      46              :             // Get the indices of the parents
      47          331 :             std::vector<int> indices;
      48          331 :             indices.push_back(-1); // Add class index
      49          674 :             transform(parents.begin(), parents.end(), back_inserter(indices), [&](const auto& p) {return find(pFeatures.begin(), pFeatures.end(), p) - pFeatures.begin(); });
      50              :             // Now we fit the discretizer of the feature, conditioned on its parents and the class i.e. discretizer.fit(X[index], X[indices] + y)
      51          331 :             std::vector<std::string> yJoinParents(Xf.size(1));
      52         1005 :             for (auto idx : indices) {
      53       239660 :                 for (int i = 0; i < Xf.size(1); ++i) {
      54       716958 :                     yJoinParents[i] += to_string(pDataset.index({ idx, i }).item<int>());
      55              :                 }
      56              :             }
      57          331 :             auto arff = ArffFiles();
      58          331 :             auto yxv = arff.factorize(yJoinParents);
      59          662 :             auto xvf_ptr = Xf.index({ index }).data_ptr<float>();
      60          331 :             auto xvf = std::vector<mdlp::precision_t>(xvf_ptr, xvf_ptr + Xf.size(1));
      61          331 :             discretizers[feature]->fit(xvf, yxv);
      62          451 :         }
      63           53 :         if (upgrade) {
      64              :             // Discretize again X (only the affected indices) with the new fitted discretizers
      65          384 :             for (auto index : indicesToReDiscretize) {
      66          662 :                 auto Xt_ptr = Xf.index({ index }).data_ptr<float>();
      67          331 :                 auto Xt = std::vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
      68         1324 :                 pDataset.index_put_({ index, "..." }, torch::tensor(discretizers[pFeatures[index]]->transform(Xt)));
      69          331 :                 auto xStates = std::vector<int>(discretizers[pFeatures[index]]->getCutPoints().size() + 1);
      70          331 :                 iota(xStates.begin(), xStates.end(), 0);
      71              :                 //Update new states of the feature/node
      72          331 :                 states[pFeatures[index]] = xStates;
      73          331 :             }
      74           53 :             const torch::Tensor weights = torch::full({ pDataset.size(1) }, 1.0 / pDataset.size(1), torch::kDouble);
      75           53 :             model.fit(pDataset, weights, pFeatures, pClassName, states);
      76           53 :         }
      77          106 :         return states;
      78       240032 :     }
      79           58 :     map<std::string, std::vector<int>> Proposal::fit_local_discretization(const torch::Tensor& y)
      80              :     {
      81              :         // Discretize the continuous input data and build pDataset (Classifier::dataset)
      82           58 :         int m = Xf.size(1);
      83           58 :         int n = Xf.size(0);
      84           58 :         map<std::string, std::vector<int>> states;
      85           58 :         pDataset = torch::zeros({ n + 1, m }, torch::kInt32);
      86           58 :         auto yv = std::vector<int>(y.data_ptr<int>(), y.data_ptr<int>() + y.size(0));
      87              :         // discretize input data by feature(row)
      88          486 :         for (auto i = 0; i < pFeatures.size(); ++i) {
      89          428 :             auto* discretizer = new mdlp::CPPFImdlp();
      90          856 :             auto Xt_ptr = Xf.index({ i }).data_ptr<float>();
      91          428 :             auto Xt = std::vector<float>(Xt_ptr, Xt_ptr + Xf.size(1));
      92          428 :             discretizer->fit(Xt, yv);
      93         1712 :             pDataset.index_put_({ i, "..." }, torch::tensor(discretizer->transform(Xt)));
      94          428 :             auto xStates = std::vector<int>(discretizer->getCutPoints().size() + 1);
      95          428 :             iota(xStates.begin(), xStates.end(), 0);
      96          428 :             states[pFeatures[i]] = xStates;
      97          428 :             discretizers[pFeatures[i]] = discretizer;
      98          428 :         }
      99           58 :         int n_classes = torch::max(y).item<int>() + 1;
     100           58 :         auto yStates = std::vector<int>(n_classes);
     101           58 :         iota(yStates.begin(), yStates.end(), 0);
     102           58 :         states[pClassName] = yStates;
     103          174 :         pDataset.index_put_({ n, "..." }, y);
     104          116 :         return states;
     105          972 :     }
     106           42 :     torch::Tensor Proposal::prepareX(torch::Tensor& X)
     107              :     {
     108           42 :         auto Xtd = torch::zeros_like(X, torch::kInt32);
     109          344 :         for (int i = 0; i < X.size(0); ++i) {
     110          302 :             auto Xt = std::vector<float>(X[i].data_ptr<float>(), X[i].data_ptr<float>() + X.size(1));
     111          302 :             auto Xd = discretizers[pFeatures[i]]->transform(Xt);
     112          906 :             Xtd.index_put_({ i }, torch::tensor(Xd, torch::kInt32));
     113          302 :         }
     114           42 :         return Xtd;
     115          302 :     }
     116              : }
        

Generated by: LCOV version 2.0-1

</html>