forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric_utils.cs
More file actions
151 lines (133 loc) · 6.36 KB
/
generic_utils.cs
File metadata and controls
151 lines (133 loc) · 6.36 KB
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
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using Tensorflow.Keras.ArgsDefinition;
using Tensorflow.Keras.Engine;
using Tensorflow.Keras.Layers;
using Tensorflow.Keras.Saving;
using Tensorflow.Train;
using System.Text.RegularExpressions;
namespace Tensorflow.Keras.Utils
{
public class generic_utils
{
private static readonly string _LAYER_UNDEFINED_CONFIG_KEY = "layer was saved without config";
/// <summary>
/// This method does not have corresponding method in python. It's close to `serialize_keras_object`.
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static LayerConfig serialize_layer_to_config(ILayer instance)
{
var config = instance.get_config();
Debug.Assert(config is LayerArgs);
return new LayerConfig
{
Config = config as LayerArgs,
ClassName = instance.GetType().Name
};
}
public static JObject serialize_keras_object(IKerasConfigable instance)
{
var config = JToken.FromObject(instance.get_config());
// TODO: change the class_name to registered name, instead of system class name.
return serialize_utils.serialize_keras_class_and_config(instance.GetType().Name, config, instance);
}
public static Layer deserialize_keras_object(string class_name, JToken config)
{
var argType = Assembly.Load("Tensorflow.Binding").GetType($"Tensorflow.Keras.ArgsDefinition.{class_name}Args");
if(argType is null)
{
return null;
}
var deserializationMethod = typeof(JToken).GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Single(x => x.Name == "ToObject" && x.IsGenericMethodDefinition && x.GetParameters().Count() == 0);
var deserializationGenericMethod = deserializationMethod.MakeGenericMethod(argType);
var args = deserializationGenericMethod.Invoke(config, null);
var layer = Assembly.Load("Tensorflow.Keras").CreateInstance($"Tensorflow.Keras.Layers.{class_name}", true, BindingFlags.Default, null, new object[] { args }, null, null);
Debug.Assert(layer is Layer);
// TODO(Rinne): _shared_object_loading_scope().set(shared_object_id, deserialized_obj)
return layer as Layer;
}
public static Layer deserialize_keras_object(string class_name, LayerArgs args)
{
var layer = Assembly.Load("Tensorflow.Keras").CreateInstance($"Tensorflow.Keras.Layers.{class_name}", true, BindingFlags.Default, null, new object[] { args }, null, null);
if (layer is null)
{
return null;
}
Debug.Assert(layer is Layer);
// TODO(Rinne): _shared_object_loading_scope().set(shared_object_id, deserialized_obj)
return layer as Layer;
}
public static LayerArgs deserialize_layer_args(string class_name, JToken config)
{
var argType = Assembly.Load("Tensorflow.Binding").GetType($"Tensorflow.Keras.ArgsDefinition.{class_name}Args");
var deserializationMethod = typeof(JToken).GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Single(x => x.Name == "ToObject" && x.IsGenericMethodDefinition && x.GetParameters().Count() == 0);
var deserializationGenericMethod = deserializationMethod.MakeGenericMethod(argType);
var args = deserializationGenericMethod.Invoke(config, null);
Debug.Assert(args is LayerArgs);
return args as LayerArgs;
}
public static FunctionalConfig deserialize_model_config(JToken json)
{
FunctionalConfig config = new FunctionalConfig();
config.Name = json["name"].ToObject<string>();
config.Layers = new List<LayerConfig>();
var layersToken = json["layers"];
foreach (var token in layersToken)
{
var args = deserialize_layer_args(token["class_name"].ToObject<string>(), token["config"]);
config.Layers.Add(new LayerConfig()
{
Config = args,
Name = token["name"].ToObject<string>(),
ClassName = token["class_name"].ToObject<string>(),
InboundNodes = token["inbound_nodes"].ToObject<List<NodeConfig>>()
});
}
config.InputLayers = json["input_layers"].ToObject<List<NodeConfig>>();
config.OutputLayers = json["output_layers"].ToObject<List<NodeConfig>>();
return config;
}
public static string to_snake_case(string name)
{
string intermediate = Regex.Replace(name, "(.)([A-Z][a-z0-9]+)", "$1_$2");
string insecure = Regex.Replace(intermediate, "([a-z])([A-Z])", "$1_$2").ToLower();
if (insecure[0] != '_')
{
return insecure;
}
return "private" + insecure;
}
/// <summary>
/// Determines whether config appears to be a valid layer config.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public static bool validate_config(JObject config)
{
return !config.ContainsKey(_LAYER_UNDEFINED_CONFIG_KEY);
}
}
}