Newer
Older
#include "Decoder.hpp"
#include "SubConfig.hpp"
Decoder::Decoder(ReadingMachine & machine) : machine(machine)
{
}
void Decoder::decode(BaseConfig & config, std::size_t beamSize, bool debug)
config.addPredicted(machine.getPredicted());
config.setState(machine.getStrategy().getInitialState());
while (true)
{
auto dictState = machine.getDict(config.getState()).getState();
auto context = config.extractContext(5,5,machine.getDict(config.getState()));
machine.getDict(config.getState()).setState(dictState);
auto neuralInput = torch::from_blob(context.data(), {(long)context.size()}, at::kLong);
auto prediction = machine.getClassifier()->getNN()(neuralInput);
int chosenTransition = -1;
for (unsigned int i = 0; i < prediction.size(0); i++)
if ((chosenTransition == -1 or prediction[i].item<float>() > prediction[chosenTransition].item<float>()) and machine.getTransitionSet().getTransition(i)->appliable(config))
chosenTransition = i;
if (chosenTransition == -1)
util::myThrow("No transition appliable !");
auto * transition = machine.getTransitionSet().getTransition(chosenTransition);
transition->apply(config);
config.addToHistory(transition->getName());
auto movement = machine.getStrategy().getMovement(config, transition->getName());
if (debug)
fmt::print(stderr, "(Transition,Newstate,Movement) = ({},{},{})\n", transition->getName(), movement.first, movement.second);
if (movement == Strategy::endMovement)
break;
config.setState(movement.first);
if (!config.moveWordIndex(movement.second))
util::myThrow("Cannot move word index !");
}
} catch(std::exception & e) {util::myThrow(e.what());}
// Force EOS when needed
if (machine.getTransitionSet().getTransition("EOS") and config.getLastNotEmptyHypConst(Config::EOSColName, config.getWordIndex()) != Config::EOSSymbol1)
{
Action shift = Action::pushWordIndexOnStack();
shift.apply(config, shift);
machine.getTransitionSet().getTransition("EOS")->apply(config);
if (debug)
fmt::print(stderr, "Forcing EOS transition\n");
}
float Decoder::getMetricScore(const std::string & metric, std::size_t scoreIndex) const
{
auto found = evaluation.find(metric);
if (found == evaluation.end())
util::myThrow(fmt::format("Cannot find metric '{}' {}\n", metric, evaluation.empty() ? "(call Decoder::evaluate() first)" : ""));
return found->second[scoreIndex];
}
float Decoder::getPrecision(const std::string & metric) const
float Decoder::getRecall(const std::string & metric) const
float Decoder::getF1Score(const std::string & metric) const
float Decoder::getAlignedAcc(const std::string & metric) const
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
std::vector<float> Decoder::getF1Scores(const std::set<std::string> & colNames) const
{
return getScores(colNames, &Decoder::getF1Score);
}
std::vector<float> Decoder::getAlignedAccs(const std::set<std::string> & colNames) const
{
return getScores(colNames, &Decoder::getAlignedAcc);
}
std::vector<float> Decoder::getRecalls(const std::set<std::string> & colNames) const
{
return getScores(colNames, &Decoder::getRecall);
}
std::vector<float> Decoder::getPrecisions(const std::set<std::string> & colNames) const
{
return getScores(colNames, &Decoder::getPrecision);
}
std::vector<float> Decoder::getScores(const std::set<std::string> & colNames, float (Decoder::* metric2score)(const std::string &) const) const
{
std::vector<float> scores;
for (auto & colName : colNames)
scores.push_back((this->*metric2score)(getMetricOfColName(colName)));
return scores;
}
std::string Decoder::getMetricOfColName(const std::string & colName) const
{
if (colName == "HEAD")
return "UAS";
if (colName == "DEPREL")
return "LAS";
if (colName == "EOS")
return "Sentences";
return colName;
}
void Decoder::evaluate(const Config & config, std::filesystem::path modelPath, const std::string goldTSV)
{
evaluation.clear();
auto predictedTSV = (modelPath/"predicted_dev.tsv").string();
std::FILE * predictedTSVFile = std::fopen(predictedTSV.c_str(), "w");
config.print(predictedTSVFile);
std::fclose(predictedTSVFile);
std::FILE * evalFromUD = popen(fmt::format("{} {} {} -v", "../scripts/conll18_ud_eval.py", goldTSV, predictedTSV).c_str(), "r");
char buffer[1024];
while (!std::feof(evalFromUD))
{
if (buffer != std::fgets(buffer, 1024, evalFromUD))
break;
if (buffer[std::strlen(buffer)-1] == '\n')
buffer[std::strlen(buffer)-1] = '\0';
if (util::doIfNameMatch(std::regex("(.*)Metric(.*)"), buffer, [this, buffer](auto sm){}))
continue;
if (util::doIfNameMatch(std::regex("(.*)\\|(.*)\\|(.*)\\|(.*)\\|(.*)"), buffer, [this, buffer](auto sm)
auto metric = util::strip(sm[1]);
for (unsigned int i = 0; i < this->evaluation[metric].size(); i++)
auto value = util::strip(sm[i+2]);
if (value.empty())
try {this->evaluation[metric][i] = std::stof(value);}
util::myThrow(fmt::format("score '{}' is not a number in line '{}'", value, buffer));