MyCaffe  1.12.2.41
Deep learning software for Windows C# programmers.
LabelMappingLayer.cs
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using MyCaffe.basecode;
6using MyCaffe.db.image;
7using MyCaffe.common;
8using MyCaffe.param;
9
10namespace MyCaffe.layers
11{
20 public class LabelMappingLayer<T> : NeuronLayer<T>
21 {
23 string m_strSource = null;
24 int m_nSourceId = 0;
25 int m_nProjectID = 0;
26 Dictionary<int, int> m_rgActualMappedLabelCounts = new Dictionary<int, int>();
27 object m_syncActualMappedLabels = new object();
28 int m_nLabelCount = 0;
29
46 : base(cuda, log, p)
47 {
48 if (db.GetVersion() != DB_VERSION.IMG_V1 && db.GetVersion() != DB_VERSION.IMG_V2)
49 throw new Exception("Currently only image databases are supported by the LabelMappingLayer.");
50
51 m_db = (IXImageDatabaseBase)db;
52 m_type = LayerParameter.LayerType.LABELMAPPING;
53 }
54
59 public override void SetNetParameterUsed(NetParameter np)
60 {
61 base.SetNetParameterUsed(np);
62
63 m_strSource = null;
64 m_nSourceId = 0;
65 m_nProjectID = np.ProjectID;
66
67 foreach (LayerParameter p in np.layer)
68 {
69 if (p.type == LayerParameter.LayerType.DATA)
70 {
71 m_strSource = p.data_param.source;
72 break;
73 }
74 }
75
76 if (m_strSource != null)
77 m_nSourceId = m_db.GetSourceID(m_strSource);
78 }
79
85 public string GetActualLabelCounts(string strSrc)
86 {
87 if (m_nLabelCount == 0)
88 m_nLabelCount = m_db.GetLabels(m_nSourceId).Count;
89
90 List<KeyValuePair<int, int>> rgKv;
91
92 lock (m_syncActualMappedLabels)
93 {
94 rgKv = m_rgActualMappedLabelCounts.OrderBy(p => p.Key).ToList();
95 }
96
97 string str = "";
98 int nIdx = 0;
99
100 for (int i = 0; i < m_nLabelCount; i++)
101 {
102 if (nIdx < rgKv.Count)
103 {
104 str += rgKv[nIdx].Key.ToString() + "->" + rgKv[nIdx].Value.ToString();
105 nIdx++;
106 }
107 else
108 {
109 str += "0";
110 }
111
112 str += ", ";
113 }
114
115 return str.TrimEnd(',', ' ');
116 }
117
118
158 public override void LayerSetUp(BlobCollection<T> colBottom, BlobCollection<T> colTop)
159 {
160 base.LayerSetUp(colBottom, colTop);
161
162 if (m_strSource != null && m_nProjectID > 0)
163 {
164 int nSrcId = m_nSourceId;
165
166 if (nSrcId > 0)
167 {
168 Dictionary<int, int> rgMapCounts = new Dictionary<int, int>();
169 Dictionary<int, List<int>> rgMaps = new Dictionary<int, List<int>>();
170 bool bHasConditions = false;
171
173 {
174 if (!rgMapCounts.Keys.Contains(map.NewLabel))
175 rgMapCounts.Add(map.NewLabel, 2);
176 else
177 rgMapCounts[map.NewLabel]++;
178
179 if (!rgMaps.Keys.Contains(map.NewLabel))
180 rgMaps.Add(map.NewLabel, new List<int>());
181
182 rgMaps[map.NewLabel].Add(map.OriginalLabel);
183
184 if (map.ConditionBoostEquals.HasValue)
185 bHasConditions = true;
186 }
187
189 {
190 string strLabelCounts = m_db.GetLabelCountsAsTextFromSourceId(nSrcId);
191
193 {
194 m_log.WriteLine("Resetting global relabeling to original labels for source '" + m_strSource + "'...");
195 m_db.ResetLabels(m_nProjectID, nSrcId);
196 }
197
198 if (rgMaps.Count > 0)
199 m_log.WriteLine("Starting global relabeling for source '" + m_strSource + "'...");
200
201 if (bHasConditions)
202 {
204 {
205 m_db.SetLabelMapping(nSrcId, map);
206 }
207 }
208 else
209 {
210 foreach (KeyValuePair<int, List<int>> kv in rgMaps)
211 {
212 m_db.UpdateLabelMapping(nSrcId, kv.Key, kv.Value);
213 }
214 }
215
216 m_db.UpdateLabelCounts(m_nProjectID, nSrcId);
217
218 if (rgMaps.Count > 0)
219 m_log.WriteLine("Global relabeling completed for source '" + m_strSource + "'...");
220
222 {
224 bool bReloadImageSet = false;
225
226 if (db != null)
227 {
228#warning ImageDatabase version 1 Only
229 string strLabelBoosts = db.GetLabelBoostsAsTextFromProject(m_nProjectID, nSrcId);
230 Dictionary<int, int> rgCounts = db.LoadLabelCounts(nSrcId);
231 string[] rgstrBoosts = m_param.labelmapping_param.label_boosts.Split(',');
232 Dictionary<int, int> rgBoostedLabelCounts = new Dictionary<int, int>();
233 double dfTotal = 0;
234
235 foreach (string strLabel in rgstrBoosts)
236 {
237 int nLabel = int.Parse(strLabel);
238
239 if (rgCounts.ContainsKey(nLabel))
240 {
241 int nCount = rgCounts[nLabel];
242 rgBoostedLabelCounts.Add(nLabel, nCount);
243 dfTotal += nCount;
244 }
245 else
246 {
247 rgBoostedLabelCounts.Add(nLabel, 0);
248 }
249 }
250
251 db.DeleteLabelBoosts(m_nProjectID, nSrcId);
252
253 foreach (KeyValuePair<int, int> kv in rgCounts)
254 {
255 double dfBoost = 0;
256
257 if (rgBoostedLabelCounts.ContainsKey(kv.Key))
258 {
259 int nCount = rgBoostedLabelCounts.Count;
260 dfBoost = (nCount == 0) ? 0 : (1.0 / (double)nCount);
261 }
262
263 db.AddLabelBoost(m_nProjectID, nSrcId, kv.Key, dfBoost);
264 }
265
266 string strNewLabelBoosts = db.GetLabelBoostsAsTextFromProject(m_nProjectID, nSrcId);
267 if (strNewLabelBoosts != strLabelBoosts)
268 bReloadImageSet = true;
269 }
270
271 if (db != null)
272 {
273 string strNewLabelCounts = db.GetLabelCountsAsTextFromSourceId(nSrcId);
274
275 if (strNewLabelCounts != strLabelCounts || bReloadImageSet)
276 db.ReloadImageSet(nSrcId);
277 }
278
279 m_log.WriteLine("WARNING: Label boosts are depreciated and soon to be removed.");
280 }
281 else
282 {
283 m_log.WriteLine("WARNING: ImageDatabase Version 2 currently does not support label mapping.");
284 }
285 }
286 }
287 }
288 }
289
299 protected override void forward(BlobCollection<T> colBottom, BlobCollection<T> colTop)
300 {
301 int nCount = colBottom[0].count();
302
303 m_log.CHECK_EQ(nCount, colBottom[0].num, "The count should equal the number of items for the label blobs.");
304 m_log.CHECK_EQ(nCount, colTop[0].count(), "The top and bottom should have the same number of items.");
305
306 double[] rgBottom = convertD(colBottom[0].update_cpu_data());
307
308 for (int i = 0; i < rgBottom.Length; i++)
309 {
310 int nLabel = m_param.labelmapping_param.MapLabel((int)rgBottom[i]);
311 rgBottom[i] = nLabel;
312
313 lock (m_syncActualMappedLabels)
314 {
315 if (!m_rgActualMappedLabelCounts.ContainsKey(nLabel))
316 m_rgActualMappedLabelCounts.Add(nLabel, 1);
317 else
318 m_rgActualMappedLabelCounts[nLabel]++;
319 }
320 }
321
322 colTop[0].mutable_cpu_data = convert(rgBottom);
323 }
324
326 protected override void backward(BlobCollection<T> colTop, List<bool> rgbPropagateDown, BlobCollection<T> colBottom)
327 {
328 }
329 }
330}
The LabelMapping class represents a single label mapping.
int? ConditionBoostEquals
Get/set the boost condition to test which if met, the new label is set, otherwise it is not.
int NewLabel
Get/set the new label.
int OriginalLabel
Get/set the original label.
The Log class provides general output in text form.
Definition: Log.cs:13
void WriteLine(string str, bool bOverrideEnabled=false, bool bHeader=false, bool bError=false, bool bDisable=false)
Write a line of output.
Definition: Log.cs:80
void CHECK_EQ(double df1, double df2, string str)
Test whether one number is equal to another.
Definition: Log.cs:239
The BlobCollection contains a list of Blobs.
The CudaDnn object is the main interface to the Low-Level Cuda C++ DLL.
Definition: CudaDnn.cs:969
/b DEPRECIATED (use DataLayer DataLabelMappingParameter instead) The LabelMappingLayer converts origi...
LabelMappingLayer(CudaDnn< T > cuda, Log log, LayerParameter p, IXDatabaseBase db)
The InnerProductLayer constructor.
override void forward(BlobCollection< T > colBottom, BlobCollection< T > colTop)
Converts the input label to the new label specified by the label mapping.
string GetActualLabelCounts(string strSrc)
Returns a string describing the actual label counts observed during training.
override void LayerSetUp(BlobCollection< T > colBottom, BlobCollection< T > colTop)
The LayerSetUp method adjusts the label boost values according to the number of mappings made to each...
override void SetNetParameterUsed(NetParameter np)
Set the parameters needed from the Net, namely the data source used.
override void backward(BlobCollection< T > colTop, List< bool > rgbPropagateDown, BlobCollection< T > colBottom)
Not implemented - The LabelMappingLayer does not perform backward.
Log m_log
Specifies the Log for output.
Definition: Layer.cs:43
LayerParameter m_param
Specifies the LayerParameter describing the Layer.
Definition: Layer.cs:47
void convert(BlobCollection< T > col)
Convert a collection of blobs from / to half size.
Definition: Layer.cs:535
double convertD(T df)
Converts a generic to a double value.
Definition: Layer.cs:1349
LayerParameter.LayerType m_type
Specifies the Layer type.
Definition: Layer.cs:35
The NeuronLayer is an interface for layers that take one blob as input (x) and produce only equally-s...
Definition: NeuronLayer.cs:22
string source
When used with the DATA parameter, specifies the data 'source' within the database....
string label_boosts
DEPRECIATED: Specifies the labels for which the label boost is to be set. When set,...
bool reset_database_labels
Specifies whether or not to reset the database labels to the original label values for the data sourc...
List< LabelMapping > mapping
Specifies the label mapping where the original label is mapped to the new label specified.
bool update_database
Specifies whether or not to directly update the database with the label mapping for the data source u...
int MapLabel(int nLabel)
Queries the mapped label for a given label.
Specifies the base parameter for all layers.
LayerType type
Specifies the type of this LayerParameter.
DataParameter data_param
Returns the parameter set when initialized with LayerType.DATA
LayerType
Specifies the layer type.
LabelMappingParameter labelmapping_param
Returns the parameter set when initialized with LayerType.LABELMAPPING
Specifies the parameters use to create a Net
Definition: NetParameter.cs:18
int ProjectID
Specifies the ID of the project that created this net param (if any).
Definition: NetParameter.cs:80
The IXDatabaseBase interface defines the general interface to the in-memory database.
Definition: Interfaces.cs:444
DB_VERSION GetVersion()
Returns the version of the MyCaffe Image Database being used.
The IXImageDatabase interface defines the eneral interface to the in-memory image database.
Definition: Interfaces.cs:1004
string GetLabelBoostsAsTextFromProject(int nProjectId, int nSrcId)
Returns the label boosts as a text string for all boosted labels within a data source associated with...
void AddLabelBoost(int nProjectId, int nSrcId, int nLabel, double dfBoost)
Add a label boost for a data source associated with a given project.
void DeleteLabelBoosts(int nProjectId, int nSrcId)
Delete all label boosts for a given data source associated with a given project.
The IXImageDatabaseBase interface defines the general interface to the in-memory image database.
Definition: Interfaces.cs:878
string GetLabelCountsAsTextFromSourceId(int nSrcId)
Returns a string with all label counts for a data source.
Dictionary< int, int > LoadLabelCounts(int nSrcId)
Returns a label lookup of counts for a given data source.
bool ReloadImageSet(int nSrcId)
Reloads the images of a data source.
The MyCaffe.basecode contains all generic types used throughout MyCaffe.
Definition: Annotation.cs:12
DB_VERSION
Defines the image database version to use.
Definition: Interfaces.cs:397
The MyCaffe.common namespace contains common MyCaffe classes.
Definition: BatchInput.cs:8
The MyCaffe.db.image namespace contains all image database related classes.
Definition: Database.cs:18
The MyCaffe.layers namespace contains all layers that have a solidified code base,...
Definition: LayerFactory.cs:15
The MyCaffe.param namespace contains parameters used to create models.
The MyCaffe namespace contains the main body of MyCaffe code that closesly tracks the C++ Caffe open-...
Definition: Annotation.cs:12