Skip to content

Commit 664e1c7

Browse files
committed
completed the CoNLLDataset load for LSTM + CRF NER example.
1 parent 95cd55d commit 664e1c7

5 files changed

Lines changed: 213 additions & 22 deletions

File tree

‎TensorFlow.NET.sln‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TensorFlowNET.Examples", "t
99
EndProject
1010
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TensorFlowNET.Core", "src\TensorFlowNET.Core\TensorFlowNET.Core.csproj", "{FD682AC0-7B2D-45D3-8B0D-C6D678B04144}"
1111
EndProject
12+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Core", "..\NumSharp\src\NumSharp.Core\NumSharp.Core.csproj", "{265765E1-C746-4241-AF2B-39B8045292D8}"
13+
EndProject
1214
Global
1315
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1416
Debug|Any CPU = Debug|Any CPU
@@ -27,6 +29,10 @@ Global
2729
{FD682AC0-7B2D-45D3-8B0D-C6D678B04144}.Debug|Any CPU.Build.0 = Debug|Any CPU
2830
{FD682AC0-7B2D-45D3-8B0D-C6D678B04144}.Release|Any CPU.ActiveCfg = Release|Any CPU
2931
{FD682AC0-7B2D-45D3-8B0D-C6D678B04144}.Release|Any CPU.Build.0 = Release|Any CPU
32+
{265765E1-C746-4241-AF2B-39B8045292D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33+
{265765E1-C746-4241-AF2B-39B8045292D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
34+
{265765E1-C746-4241-AF2B-39B8045292D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
35+
{265765E1-C746-4241-AF2B-39B8045292D8}.Release|Any CPU.Build.0 = Release|Any CPU
3036
EndGlobalSection
3137
GlobalSection(SolutionProperties) = preSolution
3238
HideSolutionNode = FALSE

‎src/TensorFlowNET.Core/TensorFlowNET.Core.csproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,8 @@ Add Word2Vec example.</PackageReleaseNotes>
6262
<Folder Include="Keras\Initializers\" />
6363
</ItemGroup>
6464

65+
<ItemGroup>
66+
<ProjectReference Include="..\..\..\NumSharp\src\NumSharp.Core\NumSharp.Core.csproj" />
67+
</ItemGroup>
68+
6569
</Project>

‎test/TensorFlowNET.Examples/TextProcess/DataHelpers.cs‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
using System.Text;
77
using System.Text.RegularExpressions;
88

9-
namespace TensorFlowNET.Examples.CnnTextClassification
9+
namespace TensorFlowNET.Examples
1010
{
1111
public class DataHelpers
1212
{
@@ -90,5 +90,65 @@ private static string clean_str(string str)
9090
str = Regex.Replace(str, @"\'s", " \'s");
9191
return str;
9292
}
93+
94+
/// <summary>
95+
/// Padding
96+
/// </summary>
97+
/// <param name="sequences"></param>
98+
/// <param name="pad_tok">the char to pad with</param>
99+
/// <returns>a list of list where each sublist has same length</returns>
100+
public static (int[][], int[]) pad_sequences(int[][] sequences, int pad_tok = 0)
101+
{
102+
int max_length = sequences.Select(x => x.Length).Max();
103+
return _pad_sequences(sequences, pad_tok, max_length);
104+
}
105+
106+
public static (int[][][], int[][]) pad_sequences(int[][][] sequences, int pad_tok = 0)
107+
{
108+
int max_length_word = sequences.Select(x => x.Select(w => w.Length).Max()).Max();
109+
int[][][] sequence_padded;
110+
var sequence_length = new int[sequences.Length][];
111+
for (int i = 0; i < sequences.Length; i++)
112+
{
113+
// all words are same length now
114+
var (sp, sl) = _pad_sequences(sequences[i], pad_tok, max_length_word);
115+
sequence_length[i] = sl;
116+
}
117+
118+
int max_length_sentence = sequences.Select(x => x.Length).Max();
119+
(sequence_padded, _) = _pad_sequences(sequences, np.repeat(pad_tok, max_length_word).Data<int>(), max_length_sentence);
120+
(sequence_length, _) = _pad_sequences(sequence_length, 0, max_length_sentence);
121+
122+
return (sequence_padded, sequence_length);
123+
}
124+
125+
private static (int[][], int[]) _pad_sequences(int[][] sequences, int pad_tok, int max_length)
126+
{
127+
var sequence_length = new int[sequences.Length];
128+
for (int i = 0; i < sequences.Length; i++)
129+
{
130+
sequence_length[i] = sequences[i].Length;
131+
Array.Resize(ref sequences[i], max_length);
132+
}
133+
134+
return (sequences, sequence_length);
135+
}
136+
137+
private static (int[][][], int[]) _pad_sequences(int[][][] sequences, int[] pad_tok, int max_length)
138+
{
139+
var sequence_length = new int[sequences.Length];
140+
for (int i = 0; i < sequences.Length; i++)
141+
{
142+
sequence_length[i] = sequences[i].Length;
143+
Array.Resize(ref sequences[i], max_length);
144+
for (int j = 0; j < max_length - sequence_length[i]; j++)
145+
{
146+
sequences[i][max_length - j - 1] = new int[pad_tok.Length];
147+
Array.Copy(pad_tok, sequences[i][max_length - j - 1], pad_tok.Length);
148+
}
149+
}
150+
151+
return (sequences, sequence_length);
152+
}
93153
}
94154
}

‎test/TensorFlowNET.Examples/TextProcess/NER/LstmCrfNer.cs‎

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System;
1+
using NumSharp;
2+
using System;
23
using System.Collections.Generic;
34
using System.IO;
45
using System.Linq;
@@ -7,6 +8,7 @@
78
using Tensorflow.Estimator;
89
using TensorFlowNET.Examples.Utility;
910
using static Tensorflow.Python;
11+
using static TensorFlowNET.Examples.DataHelpers;
1012

1113
namespace TensorFlowNET.Examples.Text.NER
1214
{
@@ -27,17 +29,32 @@ public class LstmCrfNer : IExample
2729

2830
HyperParams hp;
2931

30-
Dictionary<string, int> vocab_tags = new Dictionary<string, int>();
3132
int nwords, nchars, ntags;
3233
CoNLLDataset dev, train;
3334

35+
Tensor word_ids_tensor;
36+
Tensor sequence_lengths_tensor;
37+
Tensor char_ids_tensor;
38+
Tensor word_lengths_tensor;
39+
Tensor labels_tensor;
40+
Tensor dropout_tensor;
41+
Tensor lr_tensor;
42+
3443
public bool Run()
3544
{
3645
PrepareData();
3746
var graph = tf.Graph().as_default();
3847

3948
tf.train.import_meta_graph("graph/lstm_crf_ner.meta");
4049

50+
word_ids_tensor = graph.OperationByName("word_ids");
51+
sequence_lengths_tensor = graph.OperationByName("sequence_lengths");
52+
char_ids_tensor = graph.OperationByName("char_ids");
53+
word_lengths_tensor = graph.OperationByName("word_lengths");
54+
labels_tensor = graph.OperationByName("labels");
55+
dropout_tensor = graph.OperationByName("dropout");
56+
lr_tensor = graph.OperationByName("lr");
57+
4158
var init = tf.global_variables_initializer();
4259

4360
with(tf.Session(), sess =>
@@ -47,13 +64,85 @@ public bool Run()
4764
foreach (var epoch in range(hp.epochs))
4865
{
4966
print($"Epoch {epoch + 1} out of {hp.epochs}");
67+
run_epoch(train, dev, epoch);
5068
}
5169

5270
});
5371

5472
return true;
5573
}
5674

75+
private void run_epoch(CoNLLDataset train, CoNLLDataset dev, int epoch)
76+
{
77+
int i = 0;
78+
// iterate over dataset
79+
var batches = minibatches(train, hp.batch_size);
80+
foreach (var(words, labels) in batches)
81+
{
82+
get_feed_dict(words, labels, hp.lr, hp.dropout);
83+
}
84+
}
85+
86+
private IEnumerable<((int[][], int[])[], int[][])> minibatches(CoNLLDataset data, int minibatch_size)
87+
{
88+
var x_batch = new List<(int[][], int[])>();
89+
var y_batch = new List<int[]>();
90+
foreach(var (x, y) in data.GetItems())
91+
{
92+
if (len(y_batch) == minibatch_size)
93+
{
94+
yield return (x_batch.ToArray(), y_batch.ToArray());
95+
x_batch.Clear();
96+
y_batch.Clear();
97+
}
98+
99+
var x3 = (x.Select(x1 => x1.Item1).ToArray(), x.Select(x2 => x2.Item2).ToArray());
100+
x_batch.Add(x3);
101+
y_batch.Add(y);
102+
}
103+
104+
if (len(y_batch) > 0)
105+
yield return (x_batch.ToArray(), y_batch.ToArray());
106+
}
107+
108+
/// <summary>
109+
/// Given some data, pad it and build a feed dictionary
110+
/// </summary>
111+
/// <param name="words">
112+
/// list of sentences. A sentence is a list of ids of a list of
113+
/// words. A word is a list of ids
114+
/// </param>
115+
/// <param name="labels">list of ids</param>
116+
/// <param name="lr">learning rate</param>
117+
/// <param name="dropout">keep prob</param>
118+
private FeedItem[] get_feed_dict((int[][], int[])[] words, int[][] labels, float lr = 0f, float dropout = 0f)
119+
{
120+
int[] sequence_lengths;
121+
int[][] word_lengths;
122+
int[][] word_ids;
123+
int[][][] char_ids;
124+
125+
if (true) // use_chars
126+
{
127+
(char_ids, word_ids) = (words.Select(x => x.Item1).ToArray(), words.Select(x => x.Item2).ToArray());
128+
(word_ids, sequence_lengths) = pad_sequences(word_ids, pad_tok: 0);
129+
(char_ids, word_lengths) = pad_sequences(char_ids, pad_tok: 0);
130+
}
131+
132+
// build feed dictionary
133+
var feeds = new List<FeedItem>();
134+
feeds.Add(new FeedItem(word_ids_tensor, np.array(word_ids)));
135+
feeds.Add(new FeedItem(sequence_lengths_tensor, np.array(sequence_lengths)));
136+
137+
if(true) // use_chars
138+
{
139+
feeds.Add(new FeedItem(char_ids_tensor, np.array(char_ids)));
140+
feeds.Add(new FeedItem(word_lengths_tensor, np.array(word_lengths)));
141+
}
142+
143+
throw new NotImplementedException("get_feed_dict");
144+
}
145+
57146
public void PrepareData()
58147
{
59148
hp = new HyperParams("LstmCrfNer")

‎test/TensorFlowNET.Examples/Utility/CoNLLDataset.cs‎

Lines changed: 51 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88

99
namespace TensorFlowNET.Examples.Utility
1010
{
11-
public class CoNLLDataset : IEnumerable
11+
public class CoNLLDataset
1212
{
1313
static Dictionary<string, int> vocab_chars;
1414
static Dictionary<string, int> vocab_words;
15+
static Dictionary<string, int> vocab_tags;
1516

16-
List<Tuple<int[], int>> _elements;
1717
HyperParams _hp;
18+
string _path;
1819

1920
public CoNLLDataset(string path, HyperParams hp)
2021
{
@@ -24,22 +25,10 @@ public CoNLLDataset(string path, HyperParams hp)
2425
if (vocab_words == null)
2526
vocab_words = load_vocab(hp.filepath_words);
2627

27-
var lines = File.ReadAllLines(path);
28+
if (vocab_tags == null)
29+
vocab_tags = load_vocab(hp.filepath_tags);
2830

29-
foreach (var l in lines)
30-
{
31-
string line = l.Trim();
32-
if (string.IsNullOrEmpty(line) || line.StartsWith("-DOCSTART-"))
33-
{
34-
35-
}
36-
else
37-
{
38-
var ls = line.Split(' ');
39-
// process word
40-
var word = processing_word(ls[0]);
41-
}
42-
}
31+
_path = path;
4332
}
4433

4534
private (int[], int) processing_word(string word)
@@ -58,6 +47,20 @@ public CoNLLDataset(string path, HyperParams hp)
5847
return (char_ids, id);
5948
}
6049

50+
private int processing_tag(string word)
51+
{
52+
// 1. preprocess word
53+
if (false) // lowercase
54+
word = word.ToLower();
55+
if (false) // isdigit
56+
word = "$NUM$";
57+
58+
// 2. get id of word
59+
int id = vocab_tags.GetValueOrDefault(word, -1);
60+
61+
return id;
62+
}
63+
6164
private Dictionary<string, int> load_vocab(string filename)
6265
{
6366
var dict = new Dictionary<string, int>();
@@ -68,9 +71,38 @@ private Dictionary<string, int> load_vocab(string filename)
6871
return dict;
6972
}
7073

71-
public IEnumerator GetEnumerator()
74+
public IEnumerable<((int[], int)[], int[])> GetItems()
7275
{
73-
return _elements.GetEnumerator();
76+
var lines = File.ReadAllLines(_path);
77+
78+
int niter = 0;
79+
var words = new List<(int[], int)>();
80+
var tags = new List<int>();
81+
82+
foreach (var l in lines)
83+
{
84+
string line = l.Trim();
85+
if (string.IsNullOrEmpty(line) || line.StartsWith("-DOCSTART-"))
86+
{
87+
if (words.Count > 0)
88+
{
89+
niter++;
90+
yield return (words.ToArray(), tags.ToArray());
91+
words.Clear();
92+
tags.Clear();
93+
}
94+
}
95+
else
96+
{
97+
var ls = line.Split(' ');
98+
// process word
99+
var word = processing_word(ls[0]);
100+
var tag = processing_tag(ls[1]);
101+
102+
words.Add(word);
103+
tags.Add(tag);
104+
}
105+
}
74106
}
75107
}
76108
}

0 commit comments

Comments
 (0)