7using System.Collections.Generic;
10using System.Drawing.Drawing2D;
11using System.Drawing.Imaging;
14using System.Runtime.InteropServices;
17using System.Threading.Tasks;
30 string m_strName =
"Model";
31 string m_strProject =
null;
32 string m_strModelDesc;
37 Dictionary<string, int> m_rgActions =
new Dictionary<string, int>();
44 int m_nCurrentIdx = 0;
46 int m_nBatchSize = 16;
47 bool m_bRecreateData =
true;
48 ScoreCollection m_scores =
new ScoreCollection();
61 m_strName = gym.m_strName;
62 m_strModelDesc = gym.m_strModelDesc;
63 m_strDataset = gym.m_strDataset;
64 m_nGpuID = gym.m_nGpuID;
65 m_rgWeights = gym.m_rgWeights;
68 m_mycaffe = gym.m_mycaffe;
71 m_imgdb = gym.m_imgdb;
74 m_evtCancel = gym.m_evtCancel;
75 gym.m_evtCancel =
null;
106 m_strModelDesc = properties.
GetProperty(
"ModelDescription");
111 m_strProject = properties.
GetProperty(
"ProjectName");
112 if (
string.IsNullOrEmpty(m_strProject))
113 m_strProject =
"default";
115 string strCudaPath = properties.
GetProperty(
"CudaPath");
118 s.
GpuIds = m_nGpuID.ToString();
128 if (m_evtCancel ==
null)
132 m_mycaffe.
LoadToRun(m_strModelDesc, m_rgWeights, shape);
152 get {
return false; }
176 get {
return m_strName; }
209 if (m_blobWork !=
null)
215 if (m_mycaffe !=
null)
236 public Tuple<Bitmap, SimpleDatum>
Render(
bool bShowUi,
int nWidth,
int nHeight,
bool bGetAction)
238 List<double> rgData =
new List<double>();
239 return Render(bShowUi, nWidth, nHeight, rgData.ToArray(), bGetAction);
251 public Tuple<Bitmap, SimpleDatum>
Render(
bool bShowUi,
int nWidth,
int nHeight,
double[] rgData,
bool bGetAction)
265 return Step(-1, bGetLabel);
275 public Tuple<State, double, bool>
Step(
int nAction,
bool bGetLabel =
false,
PropertySet extraProp =
null)
277 DataState data =
new DataState();
278 ScoreCollection scores =
null;
282 if (extraProp ==
null)
283 throw new Exception(
"The extra properties are needed when querying data during the RUN phase.");
285 int nDataCount = extraProp.GetPropertyAsInt(
"DataCountRequested");
286 string strStartTime = extraProp.GetProperty(
"SeedTime");
288 int nStartIdx = m_scores.Count - nDataCount;
290 if (DateTime.TryParse(strStartTime, out dt))
291 nStartIdx = m_scores.FindIndexAt(dt, nDataCount);
293 scores = m_scores.CopyFrom(nStartIdx, nDataCount);
299 m_scores = load(out m_nDim, out m_nWidth);
303 Stopwatch sw =
new Stopwatch();
306 m_scores =
new ScoreCollection();
311 List<SimpleDatum> rgSd =
new List<SimpleDatum>();
313 for (
int i = 0; i < m_nBatchSize; i++)
323 List<ResultCollection> rgRes = m_mycaffe.
Run(rgSd, ref m_blobWork);
328 m_nDim = rgRes[0].ResultsOriginal.Count * 2;
332 for (
int i = 0; i < rgRes.Count; i++)
334 m_scores.Add(
new Score(rgSd[i].TimeStamp, rgSd[i].Index, rgRes[i]));
338 if (sw.Elapsed.TotalMilliseconds > 1000)
341 m_log.
WriteLine(
"Running model on image " + m_nCurrentIdx.ToString() +
" of " + m_ds.
TrainingSource.
ImageCount.ToString() +
" of '" + m_strDataset +
"' dataset.");
348 save(m_nDim, m_nWidth, m_scores);
352 m_nCurrentIdx = m_scores.Count;
358 float[] rgfRes = scores.Data;
363 return new Tuple<State, double, bool>(data, 0,
false);
366 private string save_file
370 string strDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
371 strDir +=
"\\MyCaffe\\test_data\\gym\\ModelGym\\";
373 if (!Directory.Exists(strDir))
374 Directory.CreateDirectory(strDir);
376 return strDir + m_strProject +
".bin";
380 private void save(
int nDim,
int nWid, ScoreCollection col)
382 string strFile = save_file;
384 using (FileStream fs = File.OpenWrite(strFile))
385 using (BinaryWriter bw =
new BinaryWriter(fs))
394 private ScoreCollection load(out
int nDim, out
int nWid)
396 string strFile = save_file;
401 if (!File.Exists(strFile))
402 return new ScoreCollection();
404 m_log.
WriteLine(
"Loading pre-run data from '" + strFile +
"'.");
406 using (FileStream fs = File.OpenRead(strFile))
407 using (BinaryReader br =
new BinaryReader(fs))
409 nDim = br.ReadInt32();
410 nWid = br.ReadInt32();
412 return ScoreCollection.Load(br);
433 log.
WriteLine(
"WARNING: This gym only supports the VALUE type, the datatype will be changed to VALUE.");
435 throw new Exception(
"This gym only supports the VALUE type.");
466 Dictionary<int, LabelDescriptor> rgLabels =
new Dictionary<int, LabelDescriptor>();
474 for (
int i = 0; i < rg.Length; i++)
476 int nLabel = (int)rg[i];
478 if (rgLabels.ContainsKey(nLabel))
479 str += rgLabels[nLabel].
Name;
486 str = str.TrimEnd(
',');
488 using (MemoryStream ms =
new MemoryStream())
490 foreach (
char ch
in str)
492 ms.WriteByte((
byte)ch);
506 get {
return m_phase; }
507 set { m_phase = value; }
511 class ScoreCollection : IEnumerable<Score>
513 List<Score> m_rgItems =
new List<Score>();
515 public ScoreCollection()
519 public float[] Scores
521 get {
return m_rgItems.Select(p => p.ScoreValue).ToArray(); }
524 public float[] Labels
526 get {
return m_rgItems.Select(p => (
float)p.Label).ToArray(); }
533 float[] rgf =
new float[m_rgItems.Count * m_rgItems[0].Results.Count * 2];
535 for (
int i = 0; i < m_rgItems.Count; i++)
537 for (
int j = 0; j < m_rgItems[i].Results.Count; j++)
539 int nCount = m_rgItems[i].Results.Count;
540 int nIdx = i * nCount * 2;
541 rgf[nIdx + j] = m_rgItems[i].Results[j].Item1;
542 rgf[nIdx + nCount + j] = m_rgItems[i].Results[j].Item2;
552 get {
return m_rgItems.Count; }
555 public Score
this[
int nIdx]
557 get {
return m_rgItems[nIdx]; }
558 set { m_rgItems[nIdx] = value; }
561 public void Add(Score r)
571 public int FindIndexAt(DateTime dt,
int nCount)
573 int nIdx = m_rgItems.Count - nCount;
575 for (
int i = m_rgItems.Count - 1; i >= 0; i--)
577 if (m_rgItems[i].TimeStamp >= dt)
589 public ScoreCollection CopyFrom(
int nStartIdx,
int nCount)
591 ScoreCollection col =
new ScoreCollection();
593 for (
int i = 0; i < nCount; i++)
595 if (nStartIdx + i < m_rgItems.Count)
596 col.Add(m_rgItems[nStartIdx + i]);
602 public IEnumerator<Score> GetEnumerator()
604 return m_rgItems.GetEnumerator();
607 IEnumerator IEnumerable.GetEnumerator()
609 return m_rgItems.GetEnumerator();
612 public static ScoreCollection Load(BinaryReader br)
614 ScoreCollection col =
new ScoreCollection();
615 int nCount = br.ReadInt32();
617 for (
int i = 0; i < nCount; i++)
619 col.Add(Score.Load(br));
625 public void Save(BinaryWriter bw)
627 bw.Write(m_rgItems.Count);
629 for (
int i = 0; i < m_rgItems.Count; i++)
631 m_rgItems[i].Save(bw);
642 List<Tuple<int, float>> m_rgResults =
new List<Tuple<int, float>>();
653 m_rgResults.Add(
new Tuple<int, float>(res1.Label, (
float)res1.Score));
657 public Score(DateTime dt,
int nIdx,
int nLabel,
float fScore, List<Tuple<int, float>> rgRes)
666 public List<Tuple<int, float>> Results
668 get {
return m_rgResults; }
673 get {
return m_nIdx; }
678 get {
return m_nLabel; }
681 public DateTime TimeStamp
686 public float ScoreValue
688 get {
return m_fScore; }
691 public static Score Load(BinaryReader br)
693 int nIdx = br.ReadInt32();
694 long lTime = br.ReadInt64();
695 int nLabel = br.ReadInt32();
696 float fScore = br.ReadSingle();
698 List<Tuple<int, float>> rgResults =
new List<Tuple<int, float>>();
699 int nCount = br.ReadInt32();
701 for (
int i = 0; i < nCount; i++)
703 int nLabel1 = br.ReadInt32();
704 float fScore1 = br.ReadSingle();
705 rgResults.Add(
new Tuple<int, float>(nLabel1, fScore1));
708 return new Score(DateTime.FromFileTime(lTime), nIdx, nLabel, fScore, rgResults);
711 public void Save(BinaryWriter bw)
714 bw.Write(m_dt.ToFileTime());
718 bw.Write(m_rgResults.Count);
720 for (
int i = 0; i < m_rgResults.Count; i++)
722 bw.Write(m_rgResults[i].Item1);
723 bw.Write(m_rgResults[i].Item2);
728 class ModelDataState : State
732 public ModelDataState()
736 public ModelDataState(ModelDataState s)
741 public override State Clone()
743 ModelDataState data =
new ModelDataState(
this);
753 public override SimpleDatum GetData(
bool bNormalize, out
int nDataLen)
755 nDataLen = (m_sd ==
null) ? 0 : m_sd.
ItemCount;
The MyCaffeControl is the main object used to manage all training, testing and running of the MyCaffe...
void LoadToRun(string strModel, byte[] rgWeights, BlobShape shape, SimpleDatum sdMean=null, TransformationParameter transParam=null, bool bForceBackward=false, bool bConvertToRunNet=true)
The LoadToRun method loads the MyCaffeControl for running only (e.g. deployment).
ResultCollection Run(int nImageIdx, bool bPad=true)
Run on a given image in the MyCaffeImageDatabase based on its image index.
The CancelEvent provides an extension to the manual cancel event that allows for overriding the manua...
bool WaitOne(int nMs=int.MaxValue)
Waits for the signal state to occur.
The Log class provides general output in text form.
void WriteLine(string str, bool bOverrideEnabled=false, bool bHeader=false, bool bError=false, bool bDisable=false)
Write a line of output.
double Progress
Get/set the progress associated with the Log.
Specifies a key-value pair of properties.
string GetProperty(string strName, bool bThrowExceptions=true)
Returns a property as a string value.
byte[] GetPropertyBlob(string strName, bool bThrowExceptions=true)
Returns a property blob as a byte array value.
int GetPropertyAsInt(string strName, int nDefault=0)
Returns a property as an integer value.
bool GetPropertyAsBool(string strName, bool bDefault=false)
Returns a property as a boolean value.
The Result class contains a single result.
The SettingsCaffe defines the settings used by the MyCaffe CaffeControl.
DB_LOAD_METHOD DbLoadMethod
Get/set the image database loading method.
string GpuIds
Get/set the default GPU ID's to use when training.
The SimpleDatum class holds a data input within host memory.
int ItemCount
Returns the number of data items.
SimpleDatum Add(SimpleDatum d)
Creates a new SimpleDatum and adds another SimpleDatum to it.
int Channels
Return the number of channels of the data.
int Width
Return the width of the data.
int Height
Return the height of the data.
int ID
Get/set the database ID of the item.
The DatasetDescriptor class describes a dataset which contains both a training data source and testin...
SourceDescriptor TrainingSource
Get/set the training data source.
The LabelDescriptor class describes a single label.
int ActiveLabel
Specifies the active label (used during training).
The SourceDescriptor class contains all information describing a data source.
List< LabelDescriptor > Labels
Get/set the list of LabelDescriptors that describe the labels used by the data items.
int ImageCount
Returns the number of images within this data source.
The Blob is the main holder of data that moves through the Layers of the Net.
virtual void Dispose(bool bDisposing)
Releases all resources used by the Blob (including both GPU and Host).
The ResultCollection contains the result of a given CaffeControl::Run.
List< Result > ResultsSorted
Returns the original results in sorted order.
double DetectedLabelOutput
Returns the detected label output depending on the result type (distance or probability) with a defau...
int DetectedLabel
Returns the detected label depending on the result type (distance or probability) with a default type...
List< Result > ResultsOriginal
Returns the original results.
[V2 Image Database] The MyCaffeImageDatabase2 provides an enhanced in-memory image database used for ...
The Model Gym runs a given Project over the dataset specified within the project where each step adva...
Tuple< Bitmap, SimpleDatum > Render(bool bShowUi, int nWidth, int nHeight, bool bGetAction)
Render the gym's current state on a bitmap and SimpleDatum.
void Initialize(Log log, PropertySet properties)
Initialize the gym with the specified properties.
Phase ActivePhase
Get/set the active phase under which the reset and next run.
Tuple< State, double, bool > Step(int nAction, bool bGetLabel=false, PropertySet extraProp=null)
Step the gym one step in the data.
double TestingPercent
Returns the testinng percent of 0, which will cause the training data to be used during testing.
DATA_TYPE SelectedDataType
Returns the selected data type.
string Name
Returns the gym's name.
Dictionary< string, int > GetActionSpace()
Returns the action space as a dictionary of name,actionid pairs.
DatasetDescriptor GetDataset(DATA_TYPE dt, Log log=null)
Returns the dataset descriptor of the dynamic dataset produced by the Gym.
ModelGym(ModelGym gym=null)
The constructor.
int UiDelay
Returns the delay to use (if any) when the user-display is visible.
void Dispose()
Release all resources used.
DATA_TYPE[] SupportedDataType
Returns the data types supported by this gym.
void Close()
Shutdown and close the gym.
bool RequiresDisplayImage
Returns true indicating that this Gym requires a display image.
byte[] ConvertOutput(Stage stage, int nN, float[] rg, out string type)
Converts the output values into the native type used by the Gym during queries.
IXMyCaffeGym Clone(PropertySet properties=null)
Create a new copy of the gym.
Tuple< State, double, bool > Reset(bool bGetLabel, PropertySet props=null)
Reset the state of the gym.
Tuple< Bitmap, SimpleDatum > Render(bool bShowUi, int nWidth, int nHeight, double[] rgData, bool bGetAction)
Render the gyms specified data.
Specifies the shape of a Blob.
SimpleDatum QueryItem(int nSrcId, int nIdx, DB_LABEL_SELECTION_METHOD? labelSelectionOverride=null, DB_ITEM_SELECTION_METHOD? imageSelectionOverride=null, int? nLabel=null, bool bLoadDataCriteria=false, bool bLoadDebugData=false)
Query an image in a given data source.
bool InitializeWithDsName1(SettingsCaffe s, string strDs, string strEvtCancel=null, PropertySet prop=null)
Initializes the image database.
DatasetDescriptor GetDatasetByName(string strDs)
Returns the DatasetDescriptor for a given data set name.
The IXImageDatabaseBase interface defines the general interface to the in-memory image database.
The IXMyCaffeGym interface is used to interact with each Gym.
The IXMyCaffeGym interface is used to interact with each Gym.
The descriptors namespace contains all descriptor used to describe various items stored within the da...
The MyCaffe.basecode contains all generic types used throughout MyCaffe.
DB_ITEM_SELECTION_METHOD
Defines the item (e.g., image or temporal item) selection method.
DB_LOAD_METHOD
Defines how to laod the items into the in-memory database.
Phase
Defines the Phase under which to run a Net.
DB_LABEL_SELECTION_METHOD
Defines the label selection method.
GYM_TYPE
Defines the gym type (if any).
DATA_TYPE
Defines the gym data type.
Stage
Specifies the stage underwhich to run a custom trainer.
The MyCaffe.common namespace contains common MyCaffe classes.
The MyCaffe.db.image namespace contains all image database related classes.
The MyCaffe.gym namespace contains all classes related to the Gym's supported by MyCaffe.
GYM_SRC_TRAIN_ID
Defines the Standard GYM Training Data Source ID's.
GYM_DS_ID
Defines the Standard GYM Dataset ID's.
GYM_SRC_TEST_ID
Defines the Standard GYM Testing Data Source ID's.
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-...