public void UpdateTrainingType(TrainingType trainingType) { using (var dataAccess = new TrainersRepo()) { dataAccess.EditTrainingType(trainingType); } }
private void btnTrainTest_Click(object sender, EventArgs e) { TrainTest(trainingType); trainedType = trainingType; lblsystemType.Text = trainedType.ToString(); btnCMatrix.Enabled = true; }
//CRUD for Training Type Model public void CreateTrainingType(TrainingType trainingType) { using (var dataAccess = new TrainersRepo()) { dataAccess.AddTrainingType(trainingType); } }
public override void TestInitialize() { base.TestInitialize(); coaches = new TestRepository(); entries = new TestTimetableEntriesRepository(); trainings = new TestTrainingsRepository(); locations = new TestLocationsRepository(); types = new TestTrainingTypesRepository(); data = GetRandom.Object <CoachData>(); var c = new Coach(data); coaches.Add(c).GetAwaiter(); trainingData = GetRandom.Object <TrainingData>(); var t = new Training(trainingData); trainings.Add(t).GetAwaiter(); trainingTypeData = GetRandom.Object <TrainingTypeData>(); var tt = new TrainingType(trainingTypeData); types.Add(tt).GetAwaiter(); locationData = GetRandom.Object <LocationData>(); var l = new Location(locationData); locations.Add(l).GetAwaiter(); obj = new TestClass(coaches, entries, trainings, locations, types); }
public async Task <ActionResult <TrainingType> > PostTrainingType(TrainingType trainingType) { _context.TrainingTypes.Add(trainingType); await _context.SaveChangesAsync(); return(CreatedAtAction("GetTrainingType", new { id = trainingType.ID }, trainingType)); }
public void TestCorrectBindings() { //Arrange DateTime now = DateTime.Now; float distance = 5.4f; TimeSpan time = new TimeSpan(2, 3, 4); float speed = 4.8f; int watt = 12; TrainingType training = TrainingType.Endurance; string comment = "test comment"; BikeType bike = BikeType.CityBike; //Act CyclingSession cyclingSession = new CyclingSession(now, distance, time, speed, watt, training, comment, bike); //Assert Assert.AreEqual(cyclingSession.When, now, "StartTime was not bound properly"); Assert.AreEqual(cyclingSession.Distance, distance, "Distance was not bound properly"); Assert.AreEqual(cyclingSession.Time, time, "Duration was not bound properly"); Assert.AreEqual(cyclingSession.AverageSpeed, speed, "Average Speed was not bound properly"); Assert.AreEqual(cyclingSession.AverageWatt, watt, "AverageWatt was not bound properly"); Assert.AreEqual(cyclingSession.TrainingType, training, "TrainingType was not bound properly"); Assert.AreEqual(cyclingSession.Comments, comment, "Comments was not bound properly"); Assert.AreEqual(cyclingSession.BikeType, bike, "BikeType was not bound properly"); }
public Training(Guid trainingID, Guid userID, DateTime date, TrainingType trainingType) { TrainingID = trainingID; UserID = userID; Date = date; TrainingType = trainingType; }
public JsonResult DeleteTrainingType(TrainingType trainingType) { var isSuccess = true; var message = string.Empty; const string url = "/TrainingType/Index"; permission = (RoleSubModuleItem)cacheProvider.Get(cacheKey) ?? roleSubModuleItemService.GetRoleSubModuleItemBySubModuleIdandRole(url, Helpers.UserSession.GetUserFromSession().RoleId); if (permission.DeleteOperation == true) { isSuccess = this.trainingTypeService.DeleteTrainingType(trainingType.Id); if (isSuccess) { message = Resources.ResourceTrainingType.MsgTrainingTypeDeleteSuccessful; } else { message = Resources.ResourceTrainingType.MsgTrainingTypeDeleteFailed; } } else { message = Resources.ResourceCommon.MsgNoPermissionToDelete; } return(Json(new { isSuccess = isSuccess, message = message }, JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> Edit(int id, [Bind("TrainingTypeId,Name,Target")] TrainingType trainingType) { if (ModelState.IsValid) { try { _context.Update(trainingType); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrainingTypeExists(trainingType.TrainingTypeId)) { ViewData["NotFound"] = "The requested trainning method is no longer available"; return(View("~/Views/Home/Index.cshtml")); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(trainingType)); }
public string GetType(byte id) { TrainingType type = _context.TrainingTypes .SingleOrDefault(l => l.Id == id); return(type.Name); }
public ActionResult Create(TrainingType trainingType) { var viewModel = new TrainingTrainersViewModel { Trainers = TrainerRepo.Trainers, Id = trainingType.Id, Name = trainingType.Name, Description = trainingType.Description, Photo = trainingType.Photo, PhotoUpload = trainingType.PhotoUpload, TrainerId = trainingType.TrainerId }; if (!ModelState.IsValid) { return(View(viewModel)); } else { if (trainingType.PhotoUpload != null) { string fileName = Path.GetFileNameWithoutExtension(trainingType.PhotoUpload.FileName); string extension = Path.GetExtension(trainingType.PhotoUpload.FileName); fileName = trainingType.Name + "_" + DateTime.Now.ToString("dd-MM-yy hh-mm-ss") + extension; trainingType.Photo = "~/Images/TrainingTypes/" + fileName; fileName = Path.Combine(Server.MapPath("~/Images/TrainingTypes/"), fileName); trainingType.PhotoUpload.SaveAs(fileName); } trainingType.Trainer = TrainerRepo.Trainers.Single(x => x.Id == trainingType.TrainerId); TrainerRepo.TrainingTypes.Add(trainingType); return(RedirectToAction("ListAll")); } }
public async Task <ResponseModel> Item(int id) { ResponseModel response = new ResponseModel(); try { TrainingType md = await _context.TrainingTypeRepository.FirstOrDefaultAsync(m => m.Id == id); TrainingTypeModel model = new TrainingTypeModel() { Id = md.Id, Name = md.Name, Description = md.Description, Precedence = md.Precedence, IsActive = md.IsActive, RowVersion = md.RowVersion, }; response.Result = model; } catch (Exception ex) { throw ex; } return(response); }
public TrainingType AddTrainingType(TrainingType trainingType) { var result = unitOfWork.TrainingTypeRepository.Insert(trainingType); unitOfWork.Save(); return(result); }
public async Task <ResponseModel> Insert(TrainingTypeModel model) { ResponseModel response = new ResponseModel(); try { TrainingType md = new TrainingType(); md.Name = model.Name; md.Description = model.Description; md.Precedence = model.Precedence; md.IsActive = model.IsActive; md.CreateBy = base.UserId; md.CreateDate = DateTime.Now; await _context.TrainingTypeRepository.AddAsync(md).ConfigureAwait(true); await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex; } return(response); }
public async Task <ResponseModel> Delete(TrainingTypeModel model) { ResponseModel response = new ResponseModel(); try { TrainingType md = await _context.TrainingTypeRepository.FirstOrDefaultAsync(m => m.Id == model.Id); if (!md.RowVersion.SequenceEqual(model.RowVersion)) { response.ResponseStatus = Core.CommonModel.Enums.ResponseStatus.OutOfDateData; return(response); } md.Deleted = true; md.UpdateBy = base.UserId; md.UpdateDate = DateTime.Now; _context.TrainingTypeRepository.Update(md); await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex; } return(response); }
public void AddTraining( int duration, TrainingType trainingType, DateTime date, string time, string description, int distance, string path) { var Training = new SDK.Model.Training(); Training.SharingFlags = 19;//public Training.Duration = TimeSpan.FromMinutes(duration); if (date == DateTime.MinValue) { date = DateTime.Now; } Training.StartDate = GetStartDate(date, time); Training.TrainingType = trainingType; Training.Description = description; Training.Distance = distance; if (!string.IsNullOrEmpty(path)) { //string s = @"c:\Users\pwujczyk\Desktop\Pamela.jpg"; byte[] bytes = File.ReadAllBytes(path); this.SportsTracker.AddTraining(Training, bytes); } else { this.SportsTracker.AddTraining(Training); } }
public async Task <IActionResult> Edit(int id, [Bind("TrainingTypeID,Name")] TrainingType trainingType) { if (id != trainingType.TrainingTypeID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(trainingType); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TrainingTypeExists(trainingType.TrainingTypeID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(trainingType)); }
// GET: TrainingTypes/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } TrainingType trainingType = manager.ReturnTrainingType(id.Value); var listTtWithTrainers = manager.ReturnTrainingTypesWithTrainers(); //TrainingType trainingTypeT = manager.ReturnTrainingType(id.Value); var viewModel = new CreateTrainingTypeViewModel() { TrainingType = trainingType, Trainers = manager.ReturnAll() }; if (trainingType == null) { return(HttpNotFound()); } return(View(viewModel)); }
public void ApplyTraining(BoterkroonSkills skill, TrainingType type) { switch (type) { case TrainingType.Slow: worstCaseScenario.GetTrainingResultsFor(skill).Add(new BoterkroonTrainingResult(BoterkroonValues.Values.NormalTrainingMinXPGain)); bestCaseScenario.GetTrainingResultsFor(skill).Add(new BoterkroonTrainingResult(BoterkroonValues.Values.NormalTrainingMaxXPGain)); worstCaseScenario.TurnsLeft -= BoterkroonValues.Values.CostNormalTraining; bestCaseScenario.TurnsLeft -= BoterkroonValues.Values.CostNormalTraining; break; case TrainingType.Fast: float skillControl = Mathf.Max(0, GetSkillControl(worstCaseScenario, skill) - BoterkroonValues.Values.StartpointFastTrainingLerp); float skillControlLerpPoint = skillControl / (1 - BoterkroonValues.Values.StartpointFastTrainingLerp); int xpGain = Mathf.FloorToInt(Mathf.Lerp(BoterkroonValues.Values.FastTrainingMinXPGain, BoterkroonValues.Values.FastTrainingMaxXPGain, skillControlLerpPoint)); worstCaseScenario.GetTrainingResultsFor(skill).Add(new BoterkroonTrainingResult(xpGain)); worstCaseScenario.TurnsLeft -= BoterkroonValues.Values.CostFastTraining; skillControl = Mathf.Max(0, GetSkillControl(bestCaseScenario, skill) - BoterkroonValues.Values.StartpointFastTrainingLerp); skillControlLerpPoint = skillControl / (1 - BoterkroonValues.Values.StartpointFastTrainingLerp); xpGain = Mathf.FloorToInt(Mathf.Lerp(BoterkroonValues.Values.FastTrainingMinXPGain, BoterkroonValues.Values.FastTrainingMaxXPGain, skillControlLerpPoint)); bestCaseScenario.GetTrainingResultsFor(skill).Add(new BoterkroonTrainingResult(xpGain)); bestCaseScenario.TurnsLeft -= BoterkroonValues.Values.CostFastTraining; break; } }
public void RemoveTrainingType(int id) { TrainingType tp = db.TrainingTypes.Find(id); db.TrainingTypes.Remove(tp); db.SaveChanges(); }
public static IEnumerable<WordCard> FilterByCounter(IEnumerable<WordCard> dictionary, CounterFilterType filterType, int filterValue, TrainingType trainingType) { IEnumerable<WordCard> result = dictionary; switch (filterType) { case CounterFilterType.Equals: result = from c in dictionary where c.Counter1[trainingType] == filterValue || c.Counter2[trainingType] == filterValue select c; break; case CounterFilterType.More: result = from c in dictionary where c.Counter1[trainingType] > filterValue || c.Counter2[trainingType] > filterValue select c; break; case CounterFilterType.Less: result = from c in dictionary where c.Counter1[trainingType] < filterValue || c.Counter2[trainingType] < filterValue select c; break; default: throw new ArgumentException("Unsupported filter type"); } return result; }
public void AddCyclingTraining(DateTime when, float?distance, TimeSpan time, float?averageSpeed, int?averageWatt, TrainingType trainingType, string comments, BikeType bikeType) { if (when > DateTime.Now) { throw new DomainException("Training is in the future"); } if (distance != null) { if ((distance <= 0) || (distance > 500)) { throw new DomainException("Distance invalid value"); } } if ((time.Ticks <= 0) || (time.TotalHours > 20)) { throw new DomainException("Time invalid value"); } if (averageSpeed != null) { if ((averageSpeed <= 0) || (averageSpeed > 60)) { throw new DomainException("Average speed invalid value"); } } if (averageWatt != null) { if ((averageWatt <= 0) || (averageWatt > 800)) { throw new DomainException("Average watt invalid value"); } } uow.CyclingTrainings.AddTraining(new CyclingSession(when, distance, time, averageSpeed, averageWatt, trainingType, comments, bikeType)); uow.Complete(); }
private TrainingType AddTrainingType() { TrainingType trainingType = new TrainingType(); AddAndAssertBaseEntityInfo(trainingType); return(trainingType); }
public ActionResult Create(TrainingTypeTrainerViewModel viewModel) { if (ModelState.IsValid) { if (viewModel.TrainingType.PhotoUpload != null) { string fileName = Path.GetFileNameWithoutExtension(viewModel.TrainingType.PhotoUpload.FileName); string extension = Path.GetExtension(viewModel.TrainingType.PhotoUpload.FileName); fileName = viewModel.TrainingType.Name + "_" + DateTime.Now.ToString("dd-MM-yy hh-mm-ss") + extension; viewModel.TrainingType.Photo = "~/Images/TrainingTypes/" + fileName; fileName = Path.Combine(Server.MapPath("~/Images/TrainingTypes/"), fileName); viewModel.TrainingType.PhotoUpload.SaveAs(fileName); } } int t = viewModel.TrainingType.TrainerId; var yy = _context.Trainers.Find(t); var model = new TrainingType() { Description = viewModel.TrainingType.Description, Name = viewModel.TrainingType.Name, Photo = viewModel.TrainingType.Photo, Trainer = yy }; _context.TrainingTypes.Add(model); _context.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Initiates Training object /// Select amount of words from dictionary to learn /// </summary> /// <param name="dictionary">Dictionary with word cards</param> /// <param name="isSwitched">Switch words in card</param> /// <param name="amount">Amount of cards to learn</param> /// <param name="maxCounter">Max counter value</param> /// <param name="type">Training type</param> /// <param name="learnedBefore">If true, Select only words that were learned in previous training type</param> public Training(WordsDictionary dictionary, bool isSwitched, int amount, int maxCounter, TrainingType type, bool learnedBefore) { this.dictionary = dictionary; this.type = type; // switch all cards if needed if (isSwitched) { foreach (var card in dictionary) card.Switched = isSwitched; } IEnumerable<WordCard> cardsList = dictionary; // get learned cards from prevois training type if (learnedBefore && type != 0) { cardsList = from c in cardsList where c.Counter1[type - 1] >= maxCounter select c; } // select cards that have counter less than maxCounter for specific training type cardsList = ( from c in cardsList where c.Counter1[type] < maxCounter orderby c.LastTrained select c) .Take(amount); cardsToLearn = cardsList.ToList(); }
private void ChangeTrainingType(TrainingType trainingType) { CurrentTrainingType = trainingType; FindViewById <ImageView>(Resource.Id.image_training_training_type).SetImageResource(MapTrainingTypeToNameIdAndImageSourceId(trainingType).Item2); FindViewById <TextView>(Resource.Id.text_training_training_type_name).Text = MapTrainingTypeToNameIdAndImageSourceId(trainingType).Item1; }
public bool CheckWord(TrainingType type, string word, string answer) { Word control; var result = false; switch (type) { case TrainingType.EngToRus: control = dictionary.Values.FirstOrDefault(x => x.English == word); result = control.Russian == answer; break; case TrainingType.RusToEng: control = dictionary[word]; result = control.English == answer; break; } return(result); }
private void TrainWithType(TrainingType type) { Thread t = new Thread(() => { double learningRate = 1; Invoke(new Action(() => { learningRate = (double)num_learningRate.Value; })); trainingFunc((int)num_iters.Value, type, learningRate, x => { error.Add(new cPoint() { x = error.Count, y = (float)x * 100 }); if (error.Count % 100 == 0) { UpdateGraph(); } }); Invoke(new Action(() => { btn_batchtrain.Enabled = true; })); }); btn_batchtrain.Enabled = false; t.IsBackground = true; t.Start(); }
private void btnSettings_Click(object sender, EventArgs e) { if (cbxGoal.SelectedItem != null && cbxGoal.SelectedItem.ToString().Equals("Strength - Maximise strength")) { TrainingType.setTrainingName(TrainingType.NAME_STRENGTH); } else if (cbxGoal.SelectedItem != null && cbxGoal.SelectedItem.ToString().Equals("Hypertrophy - Look better aesthetically")) { TrainingType.setTrainingName(TrainingType.NAME_HYPERTROPHY); } else if (cbxGoal.SelectedItem != null && cbxGoal.SelectedItem.ToString().Equals("Endurance - Maintain peak performance for longer periods of time")) { TrainingType.setTrainingName(TrainingType.NAME_ENDURANCE); } Console.WriteLine(TrainingType.getTrainingName()); String sVal = cbxDays.SelectedItem.ToString(); TrainingType.setDays((int)Char.GetNumericValue(sVal[0])); Console.WriteLine(TrainingType.getDays()); this.Controls.Clear(); this.InitializeComponent(); setButtons(); setMessage(); }
public void Train(double[][] inputs, double[][] expected, TrainingType type, int iterations) { int i, j; switch (type) { case TrainingType.BackPropogation: lock (this) { for (i = 0; i < iterations; i++) { InitializeLearning(); // set all weight changes to zero for (j = 0; j < inputs.Length; j++) { BackPropogation_TrainingSession(this, inputs[j], expected[j]); } ApplyLearning(); // apply batch of cumlutive weight changes } } break; default: throw new ArgumentException("Unexpected TrainingType"); } }
public void Create() { // Arrange var countTrainingTypes = _trainingTypes.Count; var newTrainingType = new TrainingType { Description = string.Empty, TypeTraining = "Test Training Type" }; _mock.Setup(s => s.Create(It.IsAny <TrainingTypeDTO>())).Returns <TrainingTypeDTO>(newItem => { newItem.Id = _trainingTypes.Count + 1; newItem.CreatedDate = DateTime.Now; newItem.ModifiedDate = DateTime.Now; _trainingTypes.Add(newItem); return(new OperationResult { ResultItemId = newItem.Id, Succeed = true }); }); // Act var result = _trainingTypeController.Create(newTrainingType); var operationResult = result as OkNegotiatedContentResult <IOperationResult>; // Assert Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult <IOperationResult>)); Assert.AreEqual(countTrainingTypes + 1, _trainingTypes.Count); Assert.IsTrue(operationResult.Content.Succeed); Assert.IsTrue(operationResult.Content.ResultItemId > 0); }
public void Update() { // Arrange var updateTrainingType = new TrainingType { Id = 2, Description = string.Empty, TypeTraining = "Test CrossFit" }; _mock.Setup(s => s.Update(It.IsAny <TrainingTypeDTO>())).Returns <TrainingTypeDTO>(updateValue => { updateValue.ModifiedDate = DateTime.Now; var trainingTypeIndex = _trainingTypes.FindIndex(tt => tt.Id == updateValue.Id); _trainingTypes[trainingTypeIndex] = updateValue; return(new OperationResult { ResultItemId = updateValue.Id, Succeed = true }); }); // Act var result = _trainingTypeController.Update(updateTrainingType); var operationResult = result as OkNegotiatedContentResult <IOperationResult>; // Assert Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult <IOperationResult>)); Assert.IsTrue(operationResult.Content.Succeed); Assert.IsTrue(operationResult.Content.ResultItemId > 0); Assert.AreEqual(_trainingTypes.Find(tt => tt.Id == updateTrainingType.Id).TypeTraining, updateTrainingType.TypeTraining); }
public void SetUp() { maxCards = random.Next(3, 100); dictionary = new WordsDictionary(language1, language2); for (int i = 0; i < maxCards; i++) { dictionary.Add(generator.GetCardExtra(5)); } trainingType = trainingTypeList[random.Next(trainingTypeList.Count)]; }
public void Train(double[][] inputs, double[][] expected, TrainingType type, int iterations) { int i, j; switch (type) { case TrainingType.BackPropogation: lock (this) { for (i = 0; i < iterations; i++) { InitializeLearning(); // set all weight changes to zero for (j = 0; j < inputs.Length; j++) BackPropogation_TrainingSession(this, inputs[j], expected[j]); ApplyLearning(); // apply batch of cumlutive weight changes } } //Console.WriteLine( ""); break; default: throw new ArgumentException("Unexpected TrainingType"); } }
protected internal OneRight(TrainingType type) : base(type) { }
public void TestChoose() { maxCounter = 1; type = TrainingType.Choose; Training training = new Training(dictionary, isSwitched, maxCards, maxCounter, type, learnedBefore); CheckTrainingList(training); // go trough all cards in training and choose cards var currentCard = training.NextCard(); while (currentCard != null) { var chooseList = training.Choose(); CheckChooseList(chooseList, currentCard); currentCard = training.NextCard(); } }
protected TrainingTypeModel(TrainingType type) { Type = type; }
public void TestChooseCardsLessThanType() { maxCounter = 1; type = TrainingType.Choose; Training training = new Training(dictionary, isSwitched, maxCards, maxCounter, type, learnedBefore); CheckTrainingList(training); // set word type as currentCard foreach (var card in dictionary) card.Type = WordType.Noun; var currentCard = training.NextCard(); currentCard.Type = WordType.Verb; for (int i = 0; i < dictionary.Count - 1; i++) dictionary[i].Type = currentCard.Type; var chooseList = training.Choose(cardsToChoose); CheckChooseList(chooseList, currentCard); }
private OneRightManyWrong(TrainingType type) : base(type) { }
public void TestChooseCardsMoreThanAvailableType() { maxCounter = 1; type = TrainingType.Choose; Training training = new Training(dictionary, isSwitched, maxCards, maxCounter, type, learnedBefore); CheckTrainingList(training); // set word type as currentCard var currentCard = training.NextCard(); foreach (var card in dictionary) card.Type = currentCard.Type; var chooseList = training.Choose(cardsToChoose); CheckChooseList(chooseList, currentCard); }
public void TestWrittingWHintLearnedBeforeTrueOK() { type = TrainingType.WrittingWHint; learnedBefore = true; int cardsToLearn = maxCards / 3; // set counter for choose to maxCounter for cardsToLearn foreach (var card in dictionary) card.Counter1[TrainingType.Choose] = 0; for (int i = 0; i < cardsToLearn; i++) dictionary[i].Counter1[TrainingType.Choose] = maxCounter; Training training = new Training(dictionary, isSwitched, cardsToLearn + 1, maxCounter, type, learnedBefore); CheckTrainingList(training); Assert.AreEqual(cardsToLearn, training.TotalCards, "Validating number of cards to learn"); }
public void TestChooseCards0Type() { maxCounter = 1; type = TrainingType.Choose; Training training = new Training(dictionary, isSwitched, maxCards, maxCounter, type, learnedBefore); CheckTrainingList(training); // all other cards have different type as currentCard foreach (var card in dictionary) card.Type = WordType.Noun; var currentCard = training.NextCard(); currentCard.Type = WordType.Verb; var chooseList = training.Choose(cardsToChoose); CheckChooseList(chooseList, currentCard); }
public void SetUp() { card = new CardsGenerator().GetCardExtra(5); trainingType = trainingTypeList[random.Next(trainingTypeList.Count)]; }
public void TestWrittingWHint() { maxCards = 1; type = TrainingType.WrittingWHint; Training training = new Training(dictionary, isSwitched, maxCards, maxCounter, type, learnedBefore); var currentCard = training.NextCard(); currentCard.Word2 = "Test"; string actual = training.GetHint(); string expected = "First letter is 'T', Word length is 4"; Assert.AreEqual(expected, actual, "Validating hint"); }
private ManyRight(TrainingType type) : base(type) { }
public void TestWrittingWHintLearnedBeforeTrueNOK() { type = TrainingType.WrittingWHint; learnedBefore = true; int cardsToLearn = maxCards / 3; // set counter for choose to maxCounter for all cards foreach (var card in dictionary) card.Counter1[TrainingType.Choose] = maxCounter; // select cards with counter maxCounter + 1 Training training = new Training(dictionary, isSwitched, cardsToLearn, maxCounter + 1, type, learnedBefore); CheckTrainingList(training); Assert.AreEqual(0, training.TotalCards, "Validating number of cards to learn"); }
private void TrainFor(int iterations, TrainingType type, double learningRate, Action<double> callbackWithError) { OneToManyMap<GraphMap<FeatureVector, WeightMatrix>.ILinkable, Pair<GraphMap<FeatureVector, WeightMatrix>.ILinkable, GraphMap<FeatureVector, WeightMatrix>.Link<WeightMatrix>>> backwards; Queue<GraphMap<FeatureVector, WeightMatrix>.ILinkable> inputVectors; Queue<GraphMap<FeatureVector, WeightMatrix>.ILinkable> outputVectors; GetGraphOrder(out backwards, out inputVectors, out outputVectors); List<Dictionary<string, FeatureVector>> trainingData = new List<Dictionary<string, FeatureVector>>(); // Get training data foreach (DataGridViewRow row in data_training.Rows) { string config = row.Cells[2].Value.ToString(); trainingData.Add(StateFromConfiguration(config).ToDictionary(x => x.name)); } int iterationCounter = 0; double averager = 1.0 / trainingData.Count; double learningrate = learningRate; // begin training... while (true) { double squaredTrainingError = 0; int totalTrainingNeuronCount = 0; // Matrix weight gradients Dictionary<GraphMap<FeatureVector, WeightMatrix>.Link<WeightMatrix>, Matrix> dw = new Dictionary<GraphMap<FeatureVector, WeightMatrix>.Link<WeightMatrix>, Matrix>(); foreach (var inputVector in inputVectors) { foreach (var edge in inputVector.Edges) { // make space to store the weight gradients dw[edge.Value] = new Matrix(edge.Value.Data.weights.RowCount, edge.Value.Data.weights.ColumnCount); } } foreach (var trainingCase in trainingData) { double perTrainingSquaredError = 0; int perTrainingNeuronCount = 0; // errors in all input vectors Dictionary<string, Matrix> dy = new Dictionary<string, Matrix>(); // set all feature vectors to a training case foreach (var feature in trainingCase) { if (vectors[feature.Key].Data.layer != LayerType.OUTPUT) { vectors[feature.Key].Data.state = feature.Value.state; } } // forward prop foreach (var outputVector in outputVectors) { var sources = backwards[outputVector]; outputVector.Data.state = new Matrix(outputVector.Data.state.RowCount, outputVector.Data.state.ColumnCount); foreach (var source in sources) { var x = Training.AddBiasTerm(source.a.Data.state); outputVector.Data.state += ((BaseMatrix)source.b.Data.weights * (BaseMatrix)x); } outputVector.Data.state = outputVector.Data.type.Func(outputVector.Data.state); } // Calculate errors foreach (var output in outputs) { dy[output.Data.name] = -(trainingCase[output.Data.name].state - output.Data.state); for (int i = 0; i < output.Data.state.RowCount; i++) { double error = dy[output.Data.name][i, 0]; perTrainingSquaredError += error * error; perTrainingNeuronCount++; } } squaredTrainingError += perTrainingSquaredError; totalTrainingNeuronCount += perTrainingNeuronCount; // Establish space for the input vectors foreach (var inputVec in inputVectors) { dy[inputVec.Data.name] = new Matrix(inputVec.Data.state.RowCount, inputVec.Data.state.ColumnCount); } // backprop and add to weight gradients foreach (var inputVec in inputVectors) { foreach (var edge in inputVec.Edges) { Matrix dHidden; Matrix dWeights; var x = Training.AddBiasTerm(inputVec.Data.state); GraphMap<FeatureVector, WeightMatrix>.ILinkable asd; asd = edge.Key; FeatureVector data = asd.Data; Training.BackpropLayer(dy[data.name], x, edge.Value.Data.weights, data.type, out dHidden, out dWeights); dy[inputVec.Data.name] += Training.RemoveBiasTerm(dHidden); if (type == TrainingType.Batch) { dw[edge.Value] -= dWeights; } else if (type == TrainingType.Online) { dw[edge.Value] = -dWeights; } } } // update weights if (type == TrainingType.Online) { foreach (var inputVec in inputVectors) { foreach (var edge in inputVec.Edges) { edge.Value.Data.weights = (edge.Value.Data.weights + dw[edge.Value] * learningrate); } } } } if (type == TrainingType.Batch) { // update weights foreach (var inputVec in inputVectors) { foreach (var edge in inputVec.Edges) { edge.Value.Data.weights = (edge.Value.Data.weights + dw[edge.Value] * averager * learningrate); } } } // calculate total error double totalError = Math.Sqrt(squaredTrainingError) / totalTrainingNeuronCount; callbackWithError(totalError); //Debug.WriteLine(totalError); iterationCounter++; // repeat until stopped if (iterationCounter == iterations) { break; } } }