Skip to content

Commit ff9d875

Browse files
committed
TextClassification: training set shuffling
1 parent 7a4f4fe commit ff9d875

2 files changed

Lines changed: 104 additions & 20 deletions

File tree

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

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public class DataHelpers
1313
private const string TRAIN_PATH = "text_classification/dbpedia_csv/train.csv";
1414
private const string TEST_PATH = "text_classification/dbpedia_csv/test.csv";
1515

16-
public static (NDArray, NDArray, int) build_char_dataset(string step, string model, int document_max_len, int? limit = null)
16+
public static (int[][], int[], int) build_char_dataset(string step, string model, int document_max_len, int? limit = null)
1717
{
1818
if (model != "vd_cnn")
1919
throw new NotImplementedException(model);
@@ -25,12 +25,11 @@ public static (NDArray, NDArray, int) build_char_dataset(string step, string mod
2525
char_dict["<unk>"] = 1;
2626
foreach (char c in alphabet)
2727
char_dict[c.ToString()] = char_dict.Count;
28-
var random=new Random(42);
29-
var contents = File.ReadAllLines(TRAIN_PATH).OrderBy(line=>random.NextDouble()).ToArray();
28+
var contents = File.ReadAllLines(TRAIN_PATH);
3029
var size = limit == null ? contents.Length : limit.Value;
3130

32-
var x = new NDArray(np.int32, new Shape(size, document_max_len));
33-
var y = new NDArray(np.int32, new Shape(size));
31+
var x = new int[size][];
32+
var y = new int[size];
3433
var tenth = size / 10;
3534
var percent = 0;
3635
for (int i = 0; i < size; i++)
@@ -49,10 +48,8 @@ public static (NDArray, NDArray, int) build_char_dataset(string step, string mod
4948
{
5049
if (j >= content.Length)
5150
a[j] = char_dict["<pad>"];
52-
//x[i, j] = char_dict["<pad>"];
5351
else
5452
a[j] = char_dict.ContainsKey(content[j].ToString()) ? char_dict[content[j].ToString()] : char_dict["<unk>"];
55-
//x[i, j] = char_dict.ContainsKey(content[j].ToString()) ? char_dict[content[j].ToString()] : char_dict["<unk>"];
5653
}
5754
x[i] = a;
5855
y[i] = int.Parse(parts[0]);

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

Lines changed: 100 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ protected virtual bool RunWithImportedGraph(Session sess, Graph graph)
5959
Console.WriteLine("\tDONE ");
6060

6161
var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
62-
Console.WriteLine("Training set size: " + train_x.shape[0]);
63-
Console.WriteLine("Test set size: " + valid_x.shape[0]);
62+
Console.WriteLine("Training set size: " + train_x.Length);
63+
Console.WriteLine("Test set size: " + valid_x.Length);
6464

6565
Console.WriteLine("Import graph...");
6666
var meta_file = model_name + ".meta";
@@ -161,24 +161,111 @@ protected virtual bool RunWithBuiltGraph(Session session, Graph graph)
161161
}
162162
// todo train the model
163163
return false;
164-
}
164+
}
165+
166+
// TODO: this originally is an SKLearn utility function. it randomizes train and test which we don't do here
167+
//private (NDArray, NDArray, NDArray, NDArray) train_test_split(NDArray x, NDArray y, float test_size = 0.3f)
168+
//{
169+
// Console.WriteLine("Splitting in Training and Testing data...");
170+
// int len = x.shape[0];
171+
// //int classes = y.Data<int>().Distinct().Count();
172+
// //int samples = len / classes;
173+
// int train_size = (int)Math.Round(len * (1 - test_size));
174+
// var train_x = x[new Slice(stop: train_size), new Slice()];
175+
// var valid_x = x[new Slice(start: train_size + 1), new Slice()];
176+
// var train_y = y[new Slice(stop: train_size)];
177+
// var valid_y = y[new Slice(start: train_size + 1)];
178+
// Console.WriteLine("\tDONE");
179+
// return (train_x, valid_x, train_y, valid_y);
180+
//}
165181

166-
// TODO: this originally is an SKLearn utility function. it randomizes train and test which we don't do here
167-
private (NDArray, NDArray, NDArray, NDArray) train_test_split(NDArray x, NDArray y, float test_size = 0.3f)
182+
private (int[][], int[][], int[], int[]) train_test_split(int[][] x, int[] y, float test_size = 0.3f)
168183
{
169184
Console.WriteLine("Splitting in Training and Testing data...");
170-
int len = x.shape[0];
171-
//int classes = y.Data<int>().Distinct().Count();
185+
var stopwatch = Stopwatch.StartNew();
186+
int len = x.Length;
187+
//int classes = y.Distinct().Count();
172188
//int samples = len / classes;
173-
int train_size = (int)Math.Round(len * (1 - test_size));
174-
var train_x = x[new Slice(stop: train_size), new Slice()];
175-
var valid_x = x[new Slice(start: train_size + 1), new Slice()];
176-
var train_y = y[new Slice(stop: train_size)];
177-
var valid_y = y[new Slice(start: train_size + 1)];
178-
Console.WriteLine("\tDONE");
189+
int train_size = int.Parse((len * (1 - test_size)).ToString());
190+
191+
//var train_x = new List<int[]>();
192+
//var valid_x = new List<int[]>();
193+
//var train_y = new List<int>();
194+
//var valid_y = new List<int>();
195+
196+
//for (int i = 0; i < classes; i++)
197+
//{
198+
// for (int j = 0; j < samples; j++)
199+
// {
200+
// int idx = i * samples + j;
201+
// if (idx < train_size + samples * i)
202+
// {
203+
// train_x.Add(x[idx]);
204+
// train_y.Add(y[idx]);
205+
// }
206+
// else
207+
// {
208+
// valid_x.Add(x[idx]);
209+
// valid_y.Add(y[idx]);
210+
// }
211+
// }
212+
//}
213+
var random = new Random(17);
214+
215+
// we collect indices of labels
216+
var labels = new Dictionary<int, HashSet<int>>();
217+
var shuffled_indices = Shuffle<int>(random, range(len).ToArray());
218+
foreach (var i in shuffled_indices)
219+
{
220+
var label = y[i];
221+
if (!labels.ContainsKey(i))
222+
labels[label] = new HashSet<int>();
223+
labels[label].Add(i);
224+
}
225+
226+
var train_x = new int[train_size][];
227+
var valid_x = new int[len - train_size][];
228+
var train_y = new int[train_size];
229+
var valid_y = new int[len - train_size];
230+
231+
FillWithShuffledLabels(x, y, train_x, train_y, random, labels);
232+
FillWithShuffledLabels(x, y, valid_x, valid_y, random, labels);
233+
234+
Console.WriteLine("\tDONE " + stopwatch.Elapsed);
179235
return (train_x, valid_x, train_y, valid_y);
180236
}
181237

238+
private static void FillWithShuffledLabels(int[][] x, int[] y, int[][] shuffled_x, int[] shuffled_y, Random random, Dictionary<int, HashSet<int>> labels)
239+
{
240+
int i = 0;
241+
while (i < shuffled_x.Length)
242+
{
243+
foreach (var key in Shuffle<int>(random, labels.Keys.ToArray()))
244+
{
245+
var set = labels[key];
246+
var index = set.First();
247+
if (set.Count == 0)
248+
labels.Remove(key); // remove the set as it is empty
249+
shuffled_x[i] = x[index];
250+
shuffled_y[i] = y[index];
251+
i++;
252+
}
253+
}
254+
}
255+
256+
public static T[] Shuffle<T>(Random rng, T[] array)
257+
{
258+
int n = array.Length;
259+
while (n > 1)
260+
{
261+
int k = rng.Next(n--);
262+
T temp = array[n];
263+
array[n] = array[k];
264+
array[k] = temp;
265+
}
266+
return array;
267+
}
268+
182269
private IEnumerable<(NDArray, NDArray, int)> batch_iter(NDArray inputs, NDArray outputs, int batch_size, int num_epochs)
183270
{
184271
var num_batches_per_epoch = (len(inputs) - 1) / batch_size + 1;

0 commit comments

Comments
 (0)