LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
word_dict_builder.h
Go to the documentation of this file.
1// Copyright 2021 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_LIBS_TASKS_NER_TRAIN_WORD_DICT_BUILDER
7#define DEEPLIMA_LIBS_TASKS_NER_TRAIN_WORD_DICT_BUILDER
8
9#include <string>
10#include <vector>
11#include <map>
12
13#include <static_graph/dict.h>
14
15namespace deeplima
16{
17
18template <class DataSet, class FeatExtractor>
20{
21public:
22
23 FeatExtractor preprocess(const DataSet& src,
24 const std::string& feat_extractor_init = "")
25 {
26 FeatExtractor fe(feat_extractor_init);
27
28 if (fe.needs_preprocessing())
29 {
30 typename DataSet::const_iterator it = src.begin();
31 while (src.end() != it)
32 {
33 fe.preprocess(*it);
34 it++;
35 }
36 }
37
38 return fe;
39 }
40
41 DictsHolder process(const DataSet& src,
42 int32_t min_ipm,
43 const std::string unk_str = "<<UNK>>")
44 {
45 FeatExtractor fe;
46 return process(src, fe, min_ipm, unk_str);
47 }
48
49 DictsHolder process(const DataSet& src,
50 const FeatExtractor& fe,
51 int32_t min_ipm,
52 const std::string unk_str = "<<UNK>>")
53 {
54 std::vector<std::map<std::string, uint64_t>> values(fe.size());
55 uint64_t total = 0;
56
57 typename DataSet::const_iterator it = src.begin();
58 while (src.end() != it)
59 {
60 for (size_t ifeat = 0; ifeat < fe.size(); ifeat++)
61 {
62 if (!fe.should_preprocess_feature(ifeat))
63 {
64 continue;
65 }
66
67 const std::string& feat_val = fe.feat_value(*it, ifeat);
68 if (0 == feat_val.size())
69 {
70 continue;
71 }
72 values[ifeat][feat_val]++;
73 total++;
74 }
75 it++;
76 }
77
78 DictsHolder dicts;
79 dicts.resize(values.size());
80 for (size_t ifeat = 0; ifeat < values.size(); ifeat++)
81 {
82 if (unk_str.size() > 0)
83 {
84 dicts[ifeat] = std::make_shared<StringDict>(unk_str,
85 values[ifeat].begin(), values[ifeat].end(),
86 [total, min_ipm](uint64_t c) {
87 return ipm(c, total) > min_ipm;
88 });
89 }
90 else
91 {
92 dicts[ifeat] = std::make_shared<StringDict>(values[ifeat].begin(),
93 values[ifeat].end(),
94 [total, min_ipm](uint64_t c) {
95 return ipm(c, total) > min_ipm;
96 });
97 }
98
99 }
100
101 return dicts;
102 }
103
104protected:
105
106 inline static float ipm(uint64_t count, uint64_t total)
107 {
108 return float(count * 1000000) / total;
109 }
110};
111
112} // namespace deeplima
113
114#endif
DictsHolder process(const DataSet &src, const FeatExtractor &fe, int32_t min_ipm, const std::string unk_str="<<UNK>>")
static float ipm(uint64_t count, uint64_t total)
FeatExtractor preprocess(const DataSet &src, const std::string &feat_extractor_init="")
DictsHolder process(const DataSet &src, int32_t min_ipm, const std::string unk_str="<<UNK>>")