1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use std::borrow::{Borrow, Cow};
use std::hash::Hash;
use conllx::graph::{Node, Sentence};
use failure::{format_err, Error};
use crate::{Layer, LayerValue, Numberer};
pub struct EncodingProb<'a, E>
where
E: ToOwned,
{
encoding: Cow<'a, E>,
prob: f32,
}
impl<E> EncodingProb<'static, E>
where
E: ToOwned,
{
#[allow(dead_code)]
pub(crate) fn new_from_owned(encoding: E::Owned, prob: f32) -> Self {
EncodingProb {
encoding: Cow::Owned(encoding),
prob,
}
}
}
impl<'a, E> EncodingProb<'a, E>
where
E: ToOwned,
{
pub(crate) fn new(encoding: &'a E, prob: f32) -> Self {
EncodingProb {
encoding: Cow::Borrowed(encoding),
prob,
}
}
pub fn encoding(&self) -> &E {
self.encoding.borrow()
}
pub fn prob(&self) -> f32 {
self.prob
}
}
pub trait SentenceDecoder {
type Encoding: ToOwned;
fn decode<'a, S>(&self, labels: &[S], sentence: &mut Sentence) -> Result<(), Error>
where
S: AsRef<[EncodingProb<'a, Self::Encoding>]>,
Self::Encoding: 'a;
}
pub trait SentenceEncoder {
type Encoding;
fn encode(&mut self, sentence: &Sentence) -> Result<Vec<Self::Encoding>, Error>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LayerEncoder {
layer: Layer,
}
impl LayerEncoder {
pub fn new(layer: Layer) -> Self {
LayerEncoder { layer }
}
}
impl SentenceDecoder for LayerEncoder {
type Encoding = String;
fn decode<'a, S>(&self, labels: &[S], sentence: &mut Sentence) -> Result<(), Error>
where
S: AsRef<[EncodingProb<'a, Self::Encoding>]>,
Self::Encoding: 'a,
{
assert_eq!(
labels.len(),
sentence.len() - 1,
"Labels and sentence length mismatch"
);
for (token, token_labels) in sentence
.iter_mut()
.filter_map(Node::token_mut)
.zip(labels.iter())
{
if let Some(label) = token_labels.as_ref().get(0) {
token.set_value(&self.layer, label.encoding().as_str());
}
}
Ok(())
}
}
impl SentenceEncoder for LayerEncoder {
type Encoding = String;
fn encode(&mut self, sentence: &Sentence) -> Result<Vec<Self::Encoding>, Error> {
let mut encoding = Vec::with_capacity(sentence.len() - 1);
for token in sentence.iter().filter_map(Node::token) {
let label = token
.value(&self.layer)
.ok_or_else(|| format_err!("Token without a label: {}", token.form()))?;
encoding.push(label.to_owned());
}
Ok(encoding)
}
}
pub struct CategoricalEncoder<E, V>
where
V: Eq + Hash,
{
inner: E,
numberer: Numberer<V>,
}
impl<E, V> CategoricalEncoder<E, V>
where
V: Eq + Hash,
{
pub fn new(encoder: E, numberer: Numberer<V>) -> Self {
CategoricalEncoder {
inner: encoder,
numberer,
}
}
}
impl<E> SentenceEncoder for CategoricalEncoder<E, E::Encoding>
where
E: SentenceEncoder,
E::Encoding: Clone + Eq + Hash,
{
type Encoding = usize;
fn encode(&mut self, sentence: &Sentence) -> Result<Vec<Self::Encoding>, Error> {
let encoding = self.inner.encode(sentence)?;
let categorical_encoding = encoding.into_iter().map(|e| self.numberer.add(e)).collect();
Ok(categorical_encoding)
}
}
impl<D> SentenceDecoder for CategoricalEncoder<D, D::Encoding>
where
D: SentenceDecoder,
D::Encoding: Clone + Eq + Hash,
{
type Encoding = usize;
fn decode<'a, S>(&self, labels: &[S], sentence: &mut Sentence) -> Result<(), Error>
where
S: AsRef<[EncodingProb<'a, Self::Encoding>]>,
{
let encoding = labels
.iter()
.map(|encoding_probs| {
encoding_probs
.as_ref()
.iter()
.map(|encoding_prob| {
EncodingProb::new(
self.numberer
.value(*encoding_prob.encoding())
.expect("Unknown label"),
encoding_prob.prob(),
)
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
self.inner.decode(&encoding, sentence)
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use conllx::io::Reader;
use super::{CategoricalEncoder, LayerEncoder};
use crate::{EncodingProb, Layer, Numberer, SentenceDecoder, SentenceEncoder};
static NON_PROJECTIVE_DATA: &'static str = "testdata/nonprojective.conll";
fn test_encoding<P, E, C>(path: P, mut encoder_decoder: E)
where
P: AsRef<Path>,
E: SentenceEncoder<Encoding = C> + SentenceDecoder<Encoding = C>,
C: 'static + Clone,
{
let f = File::open(path).unwrap();
let reader = Reader::new(BufReader::new(f));
for sentence in reader {
let sentence = sentence.unwrap();
let encodings = encoder_decoder
.encode(&sentence)
.unwrap()
.into_iter()
.map(|e| [EncodingProb::new_from_owned(e, 1.)])
.collect::<Vec<_>>();
let mut test_sentence = sentence.clone();
encoder_decoder
.decode(&encodings, &mut test_sentence)
.unwrap();
assert_eq!(sentence, test_sentence);
}
}
#[test]
fn categorical_encoder() {
let numberer = Numberer::new(1);
let encoder = LayerEncoder::new(Layer::Pos);
let categorical_encoder = CategoricalEncoder::new(encoder, numberer);
test_encoding(NON_PROJECTIVE_DATA, categorical_encoder);
}
}