Skip to content

Commit ed6fd47

Browse files
committed
Finished final model evaluation. Freezing graph has not been finished yet. SciSharp#248
1 parent 84440b2 commit ed6fd47

8 files changed

Lines changed: 170 additions & 39 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow
6+
{
7+
public static partial class tf
8+
{
9+
public static graph_util_impl graph_util => new graph_util_impl();
10+
public static Graph get_default_graph()
11+
{
12+
return ops.get_default_graph();
13+
}
14+
15+
public static Graph Graph() => new Graph();
16+
17+
}
18+
}
File renamed without changes.
File renamed without changes.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow
6+
{
7+
public class graph_util_impl
8+
{
9+
/// <summary>
10+
/// Replaces all the variables in a graph with constants of the same values.
11+
/// </summary>
12+
/// <param name="sess">Active TensorFlow session containing the variables.</param>
13+
/// <param name="input_graph_def">GraphDef object holding the network.</param>
14+
/// <param name="output_node_names">List of name strings for the result nodes of the graph.</param>
15+
/// <param name="variable_names_whitelist"></param>
16+
/// <param name="variable_names_blacklist"></param>
17+
/// <returns>GraphDef containing a simplified version of the original.</returns>
18+
public GraphDef convert_variables_to_constants(Session sess,
19+
GraphDef input_graph_def,
20+
string[] output_node_names,
21+
string[] variable_names_whitelist = null,
22+
string[] variable_names_blacklist = null)
23+
{
24+
// This graph only includes the nodes needed to evaluate the output nodes, and
25+
// removes unneeded nodes like those involved in saving and assignment.
26+
throw new NotImplementedException("");
27+
}
28+
29+
private string get_input_name(string node)
30+
{
31+
throw new NotImplementedException("");
32+
}
33+
}
34+
}

‎src/TensorFlowNET.Core/Train/Saving/BaseSaverBuilder.cs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,12 @@ public virtual SaverDef _build_internal(VariableV1[] names_to_saveables,
111111
var cols = graph.get_collection(collection_type);
112112
switch (cols)
113113
{
114+
case List<Tensor> values:
115+
foreach (var element in values) ;
116+
break;
117+
case List<Operation> values:
118+
foreach (var element in values) ;
119+
break;
114120
case List<VariableV1> values:
115121
foreach (var element in values) ;
116122
break;
@@ -129,6 +135,9 @@ public virtual SaverDef _build_internal(VariableV1[] names_to_saveables,
129135
case List<WhileContext> values:
130136
foreach (var element in values) ;
131137
break;
138+
case List<Object> values:
139+
foreach (var element in values) ;
140+
break;
132141
default:
133142
throw new NotImplementedException("_build_internal.check_collection_list");
134143
}
@@ -172,7 +181,7 @@ public Operation _AddRestoreOps(Tensor filename_tensor,
172181
string name = "restore_all")
173182
{
174183
var all_tensors = bulk_restore(filename_tensor, saveables, preferred_shard, restore_sequentially);
175-
var assign_ops = new List<Operation>();
184+
var assign_ops = new List<ITensorOrOperation>();
176185
int idx = 0;
177186

178187
// Load and optionally reshape on the CPU, as string tensors are not
@@ -190,7 +199,7 @@ public Operation _AddRestoreOps(Tensor filename_tensor,
190199
var saveable_tensors = all_tensors.Skip(idx).Take(saveable.specs.Length);
191200
idx += saveable.specs.Length;
192201
var restored = saveable.restore(saveable_tensors.ToArray(), shapes == null ? null : shapes.ToArray());
193-
assign_ops.Add(restored as Operation);
202+
assign_ops.Add(restored as ITensorOrOperation);
194203
}
195204

196205
return control_flow_ops.group(assign_ops.ToArray(), name: name);

‎src/TensorFlowNET.Core/Train/Saving/checkpoint_management.py.cs‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,23 +73,28 @@ private static CheckpointState generate_checkpoint_state_proto(string save_dir,
7373
string model_checkpoint_path,
7474
List<string> all_model_checkpoint_paths = null,
7575
List<float> all_model_checkpoint_timestamps = null,
76-
float? last_preserved_timestamp = null)
76+
double? last_preserved_timestamp = null)
7777
{
7878
if (all_model_checkpoint_paths == null)
7979
all_model_checkpoint_paths = new List<string>();
8080

81+
if (!all_model_checkpoint_paths.Contains(model_checkpoint_path))
82+
all_model_checkpoint_paths.Add(model_checkpoint_path);
83+
8184
// Relative paths need to be rewritten to be relative to the "save_dir"
8285
// if model_checkpoint_path already contains "save_dir".
83-
all_model_checkpoint_paths.Add(model_checkpoint_path);
8486

8587
var coord_checkpoint_proto = new CheckpointState()
8688
{
87-
ModelCheckpointPath = model_checkpoint_path,
88-
LastPreservedTimestamp = last_preserved_timestamp.Value
89+
ModelCheckpointPath = model_checkpoint_path
8990
};
9091

92+
if (last_preserved_timestamp.HasValue)
93+
coord_checkpoint_proto.LastPreservedTimestamp = last_preserved_timestamp.Value;
94+
9195
coord_checkpoint_proto.AllModelCheckpointPaths.AddRange(all_model_checkpoint_paths);
92-
coord_checkpoint_proto.AllModelCheckpointTimestamps.AddRange(all_model_checkpoint_timestamps.Select(x => (double)x));
96+
if (all_model_checkpoint_timestamps != null)
97+
coord_checkpoint_proto.AllModelCheckpointTimestamps.AddRange(all_model_checkpoint_timestamps.Select(x => (double)x));
9398

9499
return coord_checkpoint_proto;
95100
}

‎src/TensorFlowNET.Core/tf.cs‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,6 @@ public static void enable_eager_execution()
4848

4949
public static string VERSION => c_api.StringPiece(c_api.TF_Version());
5050

51-
public static Graph get_default_graph()
52-
{
53-
return ops.get_default_graph();
54-
}
55-
56-
public static Graph Graph() => new Graph();
57-
5851
public static Session Session()
5952
{
6053
defaultSession = new Session();

‎test/TensorFlowNET.Examples/ImageProcess/RetrainImageClassifier.cs‎

Lines changed: 97 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using NumSharp;
1+
using Google.Protobuf;
2+
using NumSharp;
23
using System;
34
using System.Collections.Generic;
45
using System.Diagnostics;
@@ -31,17 +32,21 @@ public class RetrainImageClassifier : IExample
3132
string summaries_dir = Path.Join(data_dir, "retrain_logs");
3233
string image_dir = Path.Join(data_dir, "flower_photos");
3334
string bottleneck_dir = Path.Join(data_dir, "bottleneck");
35+
string output_graph = Path.Join(data_dir, "output_graph.pb");
36+
string output_labels = Path.Join(data_dir, "output_labels.txt");
3437
// The location where variable checkpoints will be stored.
3538
string CHECKPOINT_NAME = Path.Join(data_dir, "_retrain_checkpoint");
3639
string tfhub_module = "https://tfhub.dev/google/imagenet/inception_v3/feature_vector/3";
40+
string final_tensor_name = "final_result";
3741
float testing_percentage = 0.1f;
3842
float validation_percentage = 0.1f;
3943
float learning_rate = 0.01f;
4044
Tensor resized_image_tensor;
4145
Dictionary<string, Dictionary<string, string[]>> image_lists;
42-
int how_many_training_steps = 200;
46+
int how_many_training_steps = 100;
4347
int eval_step_interval = 10;
4448
int train_batch_size = 100;
49+
int test_batch_size = -1;
4550
int validation_batch_size = 100;
4651
int intermediate_store_frequency = 0;
4752
int class_count = 0;
@@ -65,13 +70,13 @@ public bool Run()
6570
{
6671
(train_step, cross_entropy, bottleneck_input,
6772
ground_truth_input, final_tensor) = add_final_retrain_ops(
68-
class_count, "final_result", bottleneck_tensor,
73+
class_count, final_tensor_name, bottleneck_tensor,
6974
wants_quantization, is_training: true);
7075
});
7176

7277
/*Tensor bottleneck_tensor = graph.OperationByName("module_apply_default/hub_output/feature_vector/SpatialSqueeze");
7378
Tensor resized_image_tensor = graph.OperationByName("Placeholder");
74-
Tensor final_tensor = graph.OperationByName("final_result");
79+
Tensor final_tensor = graph.OperationByName(final_tensor_name);
7580
Tensor ground_truth_input = graph.OperationByName("input/GroundTruthInput");
7681
train_step = graph.OperationByName("train/GradientDescent");
7782
Tensor bottleneck_input = graph.OperationByName("input/BottleneckInputPlaceholder");
@@ -105,7 +110,7 @@ public bool Run()
105110

106111
// Create a train saver that is used to restore values into an eval graph
107112
// when exporting models.
108-
// var train_saver = tf.train.Saver();
113+
var train_saver = tf.train.Saver();
109114

110115
for (int i = 0; i < how_many_training_steps; i++)
111116
{
@@ -153,7 +158,7 @@ public bool Run()
153158
(string validation_summary, float validation_accuracy) = (results[0], results[1]);
154159

155160
validation_writer.add_summary(validation_summary, i);
156-
print($"{DateTime.Now}: Step {i}: Validation accuracy = {validation_accuracy * 100}% (N={len(validation_bottlenecks)})");
161+
print($"{DateTime.Now}: Step {i + 1}: Validation accuracy = {validation_accuracy * 100}% (N={len(validation_bottlenecks)})");
157162
}
158163

159164
// Store intermediate results
@@ -165,13 +170,19 @@ public bool Run()
165170
}
166171

167172
// After training is complete, force one last save of the train checkpoint.
168-
// train_saver.save(sess, CHECKPOINT_NAME);
173+
train_saver.save(sess, CHECKPOINT_NAME);
169174

170175
// We've completed all our training, so run a final test evaluation on
171176
// some new images we haven't used before.
172-
run_final_eval(sess, null, class_count, image_lists,
177+
var (test_accuracy, predictions) = run_final_eval(sess, null, class_count, image_lists,
173178
jpeg_data_tensor, decoded_image_tensor, resized_image_tensor,
174179
bottleneck_tensor);
180+
181+
// Write out the trained graph and labels with the weights stored as
182+
// constants.
183+
print($"final test accuracy: {test_accuracy}");
184+
print($"Save final result to : {output_graph}");
185+
save_graph_to_file(output_graph, class_count);
175186
});
176187

177188
return false;
@@ -188,26 +199,51 @@ public bool Run()
188199
/// <param name="decoded_image_tensor"></param>
189200
/// <param name="resized_image_tensor"></param>
190201
/// <param name="bottleneck_tensor"></param>
191-
private void run_final_eval(Session train_session, object module_spec, int class_count,
202+
private (float, NDArray) run_final_eval(Session train_session, object module_spec, int class_count,
192203
Dictionary<string, Dictionary<string, string[]>> image_lists,
193204
Tensor jpeg_data_tensor, Tensor decoded_image_tensor,
194205
Tensor resized_image_tensor, Tensor bottleneck_tensor)
195206
{
196-
/*var (eval_session, _, bottleneck_input, ground_truth_input, evaluation_step,
197-
prediction) = build_eval_session(module_spec, class_count);*/
207+
var (test_bottlenecks, test_ground_truth, test_filenames) = get_random_cached_bottlenecks(train_session, image_lists,
208+
test_batch_size, "testing", bottleneck_dir, image_dir, jpeg_data_tensor,
209+
decoded_image_tensor, resized_image_tensor, bottleneck_tensor, tfhub_module);
210+
211+
var (eval_session, _, bottleneck_input, ground_truth_input, evaluation_step,
212+
prediction) = build_eval_session(class_count);
213+
214+
var results = eval_session.run(new Tensor[] { evaluation_step, prediction },
215+
new FeedItem(bottleneck_input, test_bottlenecks),
216+
new FeedItem(ground_truth_input, test_ground_truth));
217+
218+
return (results[0], results[1]);
198219
}
199220

200-
private void build_eval_session(int class_count)
221+
private (Session, Tensor, Tensor, Tensor, Tensor, Tensor)
222+
build_eval_session(int class_count)
201223
{
202224
// If quantized, we need to create the correct eval graph for exporting.
203225
var (eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization) = create_module_graph();
204226
var eval_sess = tf.Session(graph: eval_graph);
227+
Tensor evaluation_step = null;
228+
Tensor prediction = null;
205229

206230
with(eval_graph.as_default(), graph =>
207231
{
232+
// Add the new layer for exporting.
233+
var (_, _, bottleneck_input, ground_truth_input, final_tensor) =
234+
add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor,
235+
wants_quantization, is_training: false);
208236

237+
// Now we need to restore the values from the training graph to the eval
238+
// graph.
239+
tf.train.Saver().restore(eval_sess, CHECKPOINT_NAME);
209240

241+
(evaluation_step, prediction) = add_evaluation_step(final_tensor,
242+
ground_truth_input);
210243
});
244+
245+
return (eval_sess, resized_input_tensor, bottleneck_input, ground_truth_input,
246+
evaluation_step, prediction);
211247
}
212248

213249
/// <summary>
@@ -348,20 +384,42 @@ private void variable_summaries(RefVariable var)
348384
var ground_truths = new List<long>();
349385
var filenames = new List<string>();
350386
class_count = image_lists.Keys.Count;
351-
foreach (var unused_i in range(how_many))
387+
if (how_many >= 0)
352388
{
353-
int label_index = new Random().Next(class_count);
354-
string label_name = image_lists.Keys.ToArray()[label_index];
355-
int image_index = new Random().Next(MAX_NUM_IMAGES_PER_CLASS);
356-
string image_name = get_image_path(image_lists, label_name, image_index,
357-
image_dir, category);
358-
var bottleneck = get_or_create_bottleneck(
359-
sess, image_lists, label_name, image_index, image_dir, category,
360-
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
361-
resized_input_tensor, bottleneck_tensor, module_name);
362-
bottlenecks.Add(bottleneck);
363-
ground_truths.Add(label_index);
364-
filenames.Add(image_name);
389+
// Retrieve a random sample of bottlenecks.
390+
foreach (var unused_i in range(how_many))
391+
{
392+
int label_index = new Random().Next(class_count);
393+
string label_name = image_lists.Keys.ToArray()[label_index];
394+
int image_index = new Random().Next(MAX_NUM_IMAGES_PER_CLASS);
395+
string image_name = get_image_path(image_lists, label_name, image_index,
396+
image_dir, category);
397+
var bottleneck = get_or_create_bottleneck(
398+
sess, image_lists, label_name, image_index, image_dir, category,
399+
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
400+
resized_input_tensor, bottleneck_tensor, module_name);
401+
bottlenecks.Add(bottleneck);
402+
ground_truths.Add(label_index);
403+
filenames.Add(image_name);
404+
}
405+
}
406+
else
407+
{
408+
// Retrieve all bottlenecks.
409+
foreach (var (label_index, label_name) in enumerate(image_lists.Keys.ToArray()))
410+
{
411+
foreach(var (image_index, image_name) in enumerate(image_lists[label_name][category]))
412+
{
413+
var bottleneck = get_or_create_bottleneck(
414+
sess, image_lists, label_name, image_index, image_dir, category,
415+
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
416+
resized_input_tensor, bottleneck_tensor, module_name);
417+
418+
bottlenecks.Add(bottleneck);
419+
ground_truths.Add(label_index);
420+
filenames.Add(image_name);
421+
}
422+
}
365423
}
366424

367425
return (bottlenecks.ToArray(), ground_truths.ToArray(), filenames.ToArray());
@@ -521,6 +579,20 @@ private string get_image_path(Dictionary<string, Dictionary<string, string[]>> i
521579
return full_path;
522580
}
523581

582+
/// <summary>
583+
/// Saves an graph to file, creating a valid quantized one if necessary.
584+
/// </summary>
585+
/// <param name="graph_file_name"></param>
586+
/// <param name="class_count"></param>
587+
private void save_graph_to_file(string graph_file_name, int class_count)
588+
{
589+
var (sess, _, _, _, _, _) = build_eval_session(class_count);
590+
var graph = sess.graph;
591+
var output_graph_def = tf.graph_util.convert_variables_to_constants(
592+
sess, graph.as_graph_def(), new string[] { final_tensor_name });
593+
File.WriteAllBytes(graph_file_name, output_graph_def.ToByteArray());
594+
}
595+
524596
public void PrepareData()
525597
{
526598
// get a set of images to teach the network about the new classes

0 commit comments

Comments
 (0)