1- using NumSharp ;
1+ using Google . Protobuf ;
2+ using NumSharp ;
23using System ;
34using System . Collections . Generic ;
45using 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