Exemple #1
0
    void Update()
    {
        if (Player.trainer==this)	return;

        switch(currentState){

        case States.Idle:{
            Vector3 direct = Player.trainer.transform.position - transform.position;
            if (direct.sqrMagnitude<10*10 && Vector3.Dot(direct, transform.forward)>0){

                Dialog.inDialog = true;
                Dialog.NPCobj = gameObject;
                Dialog.NPCname = "Young Trainer";
                Dialog.text = "You're a pokemon trainer right? That means we have to battle!";
                if (Dialog.doneDialog){
                    Dialog.inDialog = false;

                    currentState = States.InBattle;
                    trainerPos = transform.position - direct.normalized*10;
                    enemyTrainer = Player.trainer;
                }
            }
            break;}

        case States.InBattle:	InBattle();	break;

        }
    }
Exemple #2
0
    void LateUpdate()
    {
        pokemon = Player.pokemon;
        pokemonActive = Player.pokemonActive;
        trainer = Player.trainer;
        Quaternion camRot = transform.rotation;

        if (Dialog.NPCobj=null){
            //focus on person speaking to you
            Vector3 camFocus = Dialog.NPCobj.transform.position+Vector3.up;
            transform.rotation = Quaternion.LookRotation(transform.position-camFocus);
        }else{
            if (pokemon.obj!=null && pokemonActive){
                //focus on current pokemon
                cameraFocus = pokemon.obj.transform.position + Vector3.up;
                transform.rotation = pokemon.obj.transform.rotation * Quaternion.Euler(ax,0,0);
            }else{
                //focus on player
                cameraFocus = trainer.transform.position+Vector3.up*2;
                transform.rotation = Quaternion.Euler(ax,ay,0);
            }
        }
        transform.position = cameraFocus;
        transform.Translate(0,0,-cameraZoom);

        transform.position = Vector3.Lerp(camPos, transform.position, Time.deltaTime*5);
        transform.rotation = Quaternion.Lerp(camRot, transform.rotation, Time.deltaTime*5);
        camPos = transform.position;

        RaycastHit hit;
        Vector3 camDirect = transform.position - cameraFocus;
        if (Physics.Raycast(cameraFocus, camDirect, out hit, camDirect.magnitude, 1)){
            transform.position = hit.point - camDirect.normalized*0.5f;
        }
    }
Exemple #3
0
	void Start() {
		player = GameObject.Find ("Player");
		trainer = player.GetComponent<Trainer> ();
		player.transform.position = PlayerPosition ();
		PopulatePokemonParty ();
		PopulateItems ();
	}
Exemple #4
0
	void Start(){
		trainer = GameObject.Find("Player").GetComponent<Trainer>();
		gameObject.AddComponent<CameraControl> ();
		trainer.gameObject.AddComponent<PlayerMovement> ();
		gamegui = gameObject.AddComponent<GameGUI> ();
		gameObject.AddComponent<BattleTarget> ();
	}
Exemple #5
0
        public void Init()
        {
            _TrainerGateway = new TrainerGatewayService();

            _trainer1 = new Trainer()
            {
                Id = 1,
                FirstName = "Test FirstName 9",
                LastName = "Test LastName 9",
                Email = "*****@*****.**",
                PhoneNo = "99119911",
                Description = "A description 9"
            };

            _trainer2 = new Trainer()
            {
                Id = 2,
                FirstName = "Test FirstName 10"
            };
            _trainer3 = new Trainer()
            {
                Id = 3,
                FirstName = "Test FirstName 11"
            };
        }
Exemple #6
0
        public void Test_Delete_Trainer_in_TrainerGateway_after_Create()
        {
            _trainer2 = _TrainerGateway.Create(_trainer2);
            Assert.AreNotEqual(null, _trainer2);

            var isDeleted = _TrainerGateway.Delete(_trainer2.Id);
            Assert.AreEqual(true, isDeleted);
        }
Exemple #7
0
        internal Detector(List<FileAccess.FileEntry> fileList, int numPositive, int numNegative)
        {
            var positives = GetPositiveSamples(fileList, numPositive).ToList();
            if (numNegative <= 0) numNegative = positives.Count;
            var negatives = GetNegativeSamples(fileList, numNegative).ToList();

            _trainer = new Trainer<ImageSample>(new[] { new LBPImageLearner() }, positives, negatives);
        }
	public void InitializePanelWithTrainerData() {	
		trainer = trainerModuleScript.gameController.masterTrainer;
		currentPlayer = trainerModuleScript.gameController.masterTrainer.PlayerList[trainerModuleScript.gameController.masterTrainer.CurPlayer-1];

		textData = Time.timeScale.ToString() + "\n" + "Input Nodes: " + currentPlayer.masterPopulation.numInputNodes + "\nOutput Nodes: " + currentPlayer.masterPopulation.numOutputNodes + "\n" + trainer.GetCurrentGamePlayingState();
		logText.text = textData;
		//UpdateUIWithCurrentData();
	}
 public void OpenTrainerModule()
 {
     DebugBot.DebugFunctionCall("GameController; OpenTrainerModule(); ", debugFunctionCalls);
     if(masterTrainer == null) {  // first time running program
         masterTrainer = new Trainer();
         masterTrainer.gameControllerRef = this;
     }
     trainerUI.InitializeModuleUI();  // Sets up all panel visibility, activa/inactive states, and UI element values when module is opened
 }
Exemple #10
0
    static void Main()
    {
        Trainer regularTrainer = new Trainer("Gogo", "Strogiya", 60);
        JuniorTrainer juniorTrainer = new JuniorTrainer("Asistent", "Pomagachev", 24);
        SeniorTrainer seniorTrainer = new SeniorTrainer("Golemec", "Shisharkov", 42);
        regularTrainer.CreateCourse("OOP");
        juniorTrainer.CreateCourse("QPC");
        seniorTrainer.CreateCourse("ABC");
        seniorTrainer.DeleteCourse("DEF");
        Console.WriteLine();

        DropoutStudent applicant = new DropoutStudent("Otpadnal", "Student", 21, 1222, 3.03, "Nyama bira!!!");
        applicant.Reapply();
        Console.WriteLine();

        var people = new List<Person>
        {
            new Person("Georgi", "Georgiev", 20),
            new Trainer("Ivan", "Ivanov", 28),
            new JuniorTrainer("Ivan", "Ivanov Jr.", 19),
            new SeniorTrainer("Ivan", "Ivanov Sr.", 35),
            new Student("Pesho", "Peshev", 22, 1234, 5.75),
            new DropoutStudent("Misho", "Mihaylov", 25, 1234, 3.5, "Too few women on campus."),
            new GraduateStudent("Golemets", "Golemiya", 31, 1234, 5.25),
            new CurrentStudent("Stamat", "Botusharov", 23, 1234, 3.25, "OOP"),
            new OnlineStudent("Myrzeliv", "Myrzelivets", 21, 1234, 2.5, "OOP"),
            new OnsiteStudent("Svetlin", "Nakov", 34, 1234, 6, "OOP", 15),
            new CurrentStudent("Irokentij", "Portokalov", 43, 1234, 4.25, "QPC"),
            new OnlineStudent("Onufrij", "Popryckov", 63, 1234, 5.15, "QPC"),
            new OnsiteStudent("Maria", "Ivanova", 19, 1234, 5.86, "QPC", 12)
        };


        //people.Add(new Person("", "Georgiev", 20));
        //people.Add(new Person("Georgi", " ", 10));
        //people.Add(new Person("Georgi", "Georgiev", -2));
        //people.Add(new Person("Georgi", "Georgiev", 101));
        //people.Add(new Student("Pesho", "Peshev", 22, 11, 2.5));
        //people.Add(new Student("Pesho", "Peshev", 22, 1202022, 2.5));
        //people.Add(new Student("Pesho", "Peshev", 22, 1234, 1.9));
        //people.Add(new Student("Pesho", "Peshev", 22, 1234, 7.5));
        //people.Add(new DropoutStudent("Misho", "Mihaylov", 25, 1234, 3.5, ""));
        //people.Add(new CurrentStudent("Stamat", "Botusharov", 23, 1234, 3.25, " "));

        List<CurrentStudent> currentStudents = people.Where(a => a is CurrentStudent).ToList().Cast<CurrentStudent>().ToList();
        var sortedCurrentStudents = currentStudents.OrderBy(a => a.AverageGrade);

        Console.WriteLine("List of current students (sorted by average grade):");
        Console.WriteLine();

        foreach (var student in sortedCurrentStudents)
        {
            Console.WriteLine(student);
        }
    }
Exemple #11
0
        static void Main(string[] args)
        {
            try
            {
                for (var noise = 0; noise < 2; noise++)
                {
                    var error = 0.05 * noise;

                    List<Sample> pointsPos, pointsNeg;

                    var flippedLabels = GenerateSamples(error, out pointsPos, out pointsNeg);

                    var t = new Trainer<Sample>(new ILearner<Sample>[] { new Sample.Learner(21) }, pointsPos, pointsNeg);

                    var convergence = 0;
                    var prev = 0;
                    Console.WriteLine("Noise: " + error + " (" + flippedLabels + " label errors)");
                    for (var i = 0; i < 1000; i++)
                    {
                        var cost = t.AddLayer();

                        if (float.IsNaN(cost))
                        {
                            Console.WriteLine("Terminated after " + i + " layers.");
                            break;
                        }

                        //Console.WriteLine("Loss = " + (float)cost);
                        var testErrors = TestTrainer(t.Classifier, pointsPos, pointsNeg);
                        var veriErrors = TestTrainer(t.Classifier);

                        if (testErrors == prev) convergence++;
                        else convergence = 0;
                        if (convergence > 19)
                        {
                            Console.WriteLine("Fully trained after " + (i - 9) + " layers.");
                            break;
                        }
                        else if ((i + 1) % 10 == 0)
                        {
                            Console.WriteLine("[" + testErrors + " / " + veriErrors + " ] errors after " + (i + 1) + " layers.");
                        }
                        prev = testErrors;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadKey();
        }
Exemple #12
0
        public void Test_not_Deleting_Trainer_in_TrainerGateway()
        {
            int noneExistingId = -1;

            var trainer = new Trainer()
            {
                Id = noneExistingId
            };

            var isDeleted = _TrainerGateway.Delete(trainer.Id);

            Assert.AreEqual(false, isDeleted);
        }
Exemple #13
0
        public void Test_not_Updating_Trainer_in_TrainerGateway()
        {
            int noneExistingId = -1;

            var trainer = new Trainer()
            {
                Id = noneExistingId
            };

            var _recivedTrainer = _TrainerGateway.Update(trainer);

            Assert.AreEqual(trainer.Id, _recivedTrainer.Id);
        }
Exemple #14
0
 public ActionResult Create(Trainer trainer)
 {
     facade.GetTrainerGateway().Create(new Trainer()
     {
         Id = trainer.Id,
         Picture = trainer.Picture,
         Description = trainer.Description,
         Email = trainer.Email,
         FirstName = trainer.FirstName,
         LastName = trainer.LastName,
         PhoneNo = trainer.PhoneNo
     });
     return RedirectToAction("Options", "Trainer");
 }
        public Monster BuildMonster(string name, string description, Trainer assignedTrainer)
        {
            double[] trainingPoints = new double[StatList.ArrayLength];
            MakeTrainingPoints(trainingPoints);

            double[] affinities = new double[AffinityList.ArrayLength];
            MakeAffinities(affinities);

            double[] elementalMastery = new double[ElementList.ArrayLength];
            MakeElementalMastery(elementalMastery);

            Monster monster = new Monster(name, description, affinities, elementalMastery, trainingPoints, assignedTrainer);
            return monster;
        }
        public Trainer BuildTrainer(string name, string description)
        {
            double[] trainingPoints = new double[StatList.ArrayLength];
            MakeTrainingPoints(trainingPoints);

            double[] affinities = new double[AffinityList.ArrayLength];
            MakeAffinities(affinities);

            double[] elementalMastery = new double[ElementList.ArrayLength];
            MakeElementalMastery(elementalMastery);

            Trainer player = new Trainer(name, description, affinities, elementalMastery, trainingPoints);
            return player;
        }
    void Start()
    {
        ptron = new Perceptron(3);

        //Make 2,000 training points.
        for (int i = 0; i < training.Length; i++)
        {
            float x = Random.Range(-m_Width/2,m_Width/2);
            float y = Random.Range(-m_Height/2,m_Height/2);
            //Is the correct answer 1 or -1?
            int answer = 1;
            if (y < f(x)) answer = -1;
            training[i] = new Trainer(x, y, answer);
        }
    }
Exemple #18
0
	void Update(){
		if (Player.trainer==this)	return;
		
		if (Input.GetKeyDown (KeyCode.Escape)) {
			Dialog.doneDialog=true;
		}
		
		switch(currentState){
			
			case States.Idle:{
				Vector3 direct = Player.trainer.transform.position - transform.position;
				if (direct.sqrMagnitude<10*10 && Vector3.Dot(direct, transform.forward)>0){
					
					Dialog.inDialog = true;
					Dialog.NPCobj = gameObject;
					Dialog.NPCname = "Young Trainer";
					Dialog.text = "You're a pokemon trainer right? That means we have to battle!";
					if (Dialog.doneDialog){
						Dialog.inDialog = false;
						
						currentState = States.InBattle;
						trainerPos = transform.position - direct.normalized*10;
						enemyTrainer = Player.trainer;
					}
				}
				break;
			}
				
			case States.InBattle:	InBattle();	break;
			
			case States.Defeated: {
				Dialog.inDialog = true;
				Dialog.NPCobj = gameObject;
				Dialog.NPCname = "Young Trainer";
				Dialog.text = "You've beaten me!!";
				if (Dialog.doneDialog){
					Dialog.inDialog = false;
					currentState = States.Inactive;
				}
				break;
			}
			case States.Inactive: {
				//add timer here to reset AI state to idle after a period of time
				break;
			}
			
		}
	}
Exemple #19
0
        public static void Test(string trainImagesPath, string trainLabelsPath, string testImagesPath, string testLabelsPath)
        {
            LoadDataSet(trainImagesPath, trainLabelsPath, testImagesPath, testLabelsPath);
            GC.Collect();

            var network   = NetworkBuilder.CreateMnist(trainDataSet);

            Console.WriteLine("Initial");
            Test(network, testDataSet);
            Console.WriteLine("StartLearning");

            var cost = Double.PositiveInfinity;
            var timer = new Stopwatch();
            timer.Start();

            var optimizer = new GradientDescent<Matrix, Vector>(3, 0.0007, 1,
                x => {
                    timer.Stop();
                    Console.Write("Ignored {0}% of samples ", 100 * NeuralNetwork<Matrix>.counter / (double)trainDataSet.Inputs.Count());
                    Console.WriteLine("and gradient descent step time: {0} ms", timer.ElapsedMilliseconds);
                    NeuralNetwork<Matrix>.counter = 0;
                    Console.Write("trainSet: ");
                    cost = Test(x, trainDataSet, cost);
                    Console.Write(" || ");
                    Console.Write("testSet:  ");
                    Test(x, testDataSet);
                    Console.WriteLine();
                    timer.Reset();
                    timer.Start();
                });

            var trainer = new Trainer<Matrix, Vector>(optimizer);

            for (var i = 0; i < 10; ++i)
            {
                Console.WriteLine("Generation {0}", i);
                trainer.Train(network, trainDataSet.Set);

                optimizer.IterationCount  += 1;
                optimizer.InitialStepSize *= 2;
            }

            Console.WriteLine("EndLearning");
            Test(network, testDataSet);
        }
        static void Main()
        {
            AbstractLector professor = new Professor { Name = "Ivan Ivanov", Income = 25000, VacationDays = 45, WorkFromHomeDays = 30 };
            AbstractLector teacher = new Teacher { Name = "Petar Petrov", Income = 15000, VacationDays = 30, WorkFromHomeDays = 15 };
            AbstractLector trainer = new Trainer { Name = "Georgi Georgiev", Income = 10000, VacationDays = 22 };

            LectorsList lectors = new LectorsList();
            lectors.Attach(professor);
            lectors.Attach(teacher);
            lectors.Attach(trainer);

            lectors.Accept(new IncomeVisitor());

            professor.Accept(new HomeWorkVisitor());

            lectors.Detach(trainer);
            lectors.Accept(new IncomeVisitor());
        }
Exemple #21
0
    public Pokemon(int number, Trainer trainer = null, bool isPlayer = false, int level = 5)
    {
        this.number = number;
        this.trainer = trainer;
        this.isPlayer = isPlayer;

        name = GetName(number);
        icon = GetIcon(number);
        this.level = level;

        hp = 1;
        attack = TotalAttack();
        defence = TotalDefence();
        speed = TotalSpeed ();
        pp = 1;
        xp = Random.value;
        PopulateMoves();
    }
Exemple #22
0
 static void Main()
 {
     List<object> list = new List<object>();
     Person stamat = new Person("Stamat", "Stamtov", 18);
     Trainer vladi = new Trainer("Vladi", "Vargala", 24);
     SeniorTrainer nakov = new SeniorTrainer("Svetin", "Nakov", 22);
     JuniorTrainer niki = new JuniorTrainer("Nikolay", "Bankin", 18);
     niki.CreateCourse("Tvardost na betona");
     nakov.DeleteCourse("Tvardost na betona");
     Student mimi = new Student("Mariya", "Ilieva", 25, 1345, 4.60);
     DropoutStudent vasko = new DropoutStudent("Vasko", "Keca", 17, 300, 5, "Music");
     vasko.Reapply();
     GraduateStudent nobody = new GraduateStudent("Misho", "Birata", 40, 20, 3.40);
     OnlineStudent uncleTony = new OnlineStudent("Uncle", "Antony", 25, 7, 5, "OOP");
     CurrentStudent me = new CurrentStudent("Gosho", "Lyaskov", 28, 1, 5.4, "OOP");
     CurrentStudent you = new CurrentStudent("Pesho", "Peshev", 28, 2, 5.1, "OOP");
     CurrentStudent somebody = new CurrentStudent("Uncnown", "Person", 14, 190, 6, "OOP");
     AddtoList(list, stamat, vladi, nakov, niki, mimi, vasko, nobody, uncleTony, me, you, somebody);
     list.Where(x => x is CurrentStudent).OrderByDescending(x => ((Student)x).StudentAverageGrade).ToList().ForEach(x => Console.WriteLine(x.ToString()));
 }
Exemple #23
0
	public static void ThrowPokeBall(Trainer trainer){
		//find the nearest pokemon to capture, withing the correct direction I guess
		float dist = 1000000;
		GameObject pokemonOb = null;
		foreach(GameObject poke in GameObject.FindGameObjectsWithTag("pokemon")){
			Vector3 direct = trainer.transform.position-poke.transform.position;
			if (direct.sqrMagnitude<dist){
				dist = direct.sqrMagnitude;
				pokemonOb = poke;
			}
		}

		GameObject ball = (GameObject)Instantiate(Resources.Load("Pokeball"));
		ball.transform.position = GameObject.Find("_PokeballHolder").transform.position;

		if (pokemonOb!=null){
			Vector3 direct = pokemonOb.transform.position - ball.transform.position;
			ball.rigidbody.AddForce( direct.normalized*500+ Vector3.up * direct.magnitude/50);
			ball.GetComponent<Pokeball>().trainer = trainer;
		}
	}
Exemple #24
0
        static void Main()
        {
            var nasko = new Trainer("Atanas", "Rusenov", 21);
            var fill = new JuniorTrainer("Filip", "Kolev", 28);
            var nakov = new SeniorTrainer("Svetlin", "Nakov", 60);

            var mark = new GraduateStudent("Марк", "Зукърбъргов", 38, 120511, 6.00);
            var mitio = new DropoutStudent("Митьо", "Крика", 40, 343535, 2.30, "Много големи ръки");
            var djordjano = new CurrentStudent("Djordjano", "Djordjankata", 25, 0888155,"Introducing to singing");
            var baiVulcho = new OnlineStudent("Бай", "Вълчо", 73, 4444, 5.60,"OOP");
            var lelqVanche = new OnsiteStudent("Леля", "Ванче", 57, 12034, 4.89, "Аdvanced C#", 20);

            nakov.DeleteCourse("PHP");
            fill.CreateCourse("Advanced C#");
            nasko.CreateCourse("Kopane");
            nakov.DeleteCourse("Kopane"); // Nasko, what are you doing?!?
            Console.WriteLine();

            var persons = new List<Person>()
            {
                nasko,
                fill,
                nakov,
                mark,
                mitio,
                djordjano,
                baiVulcho,
                lelqVanche
            };

            var currentStudents = persons.Where(student => student is CurrentStudent)
                .OrderBy(student => ((Student)student).AverageGrade)
                .Select(student => student);

            foreach (var currentStudent in currentStudents)
            {
                Console.WriteLine(currentStudent);
            }
        }
Exemple #25
0
        public static void Test(string trainImagesPath, string trainLabelsPath, string testImagesPath, string testLabelsPath)
        {
            var dataSet   = LoadDataSet(trainImagesPath, trainLabelsPath, testImagesPath, testLabelsPath);
            GC.Collect();

            var network   = NetworkBuilder.Create(dataSet
                            , new Tanh()
                            , new List<int> { 50 }
                            );

            var cost = Double.PositiveInfinity;
            var optimizer = new GradientDescent<Vector, Vector>(5, 0.02, 2,
                x => {
                    Console.Write("trainSet: ");
                    cost = Test(x, dataSet, cost);
                    Console.Write(" || ");
                    Console.Write("testSet:  ");
                    Test(x, testDataSet);
                    Console.WriteLine();
                });

            var trainer   = new Trainer<Vector, Vector>(optimizer);

            Console.WriteLine("Initial");
            Test(network, dataSet);
            Console.WriteLine("StartLearning");

            for (var i = 0; i < 3; ++i)
            {
                Console.WriteLine("next generation");
                trainer.Train(network, dataSet.Set);
                optimizer.IterationCount += 1;
                optimizer.InitialStepSize *= 2;
            }

            Console.WriteLine("EndLearning");
            Test(network, testDataSet);
        }
        public static void computeConsistency(LangDescriptor language, bool report)
        {
            if (report)
            {
                Console.WriteLine("-----------------------------------");
                Console.WriteLine(language.name);
                Console.WriteLine("-----------------------------------");
            }
            Corpus corpus = new Corpus(language.corpusDir, language);

            corpus.train();
            // a map of feature vector to list of exemplar indexes of that feature
            MyMultiMap <FeatureVectorAsObject, int> wsContextToIndex   = new MyMultiMap <FeatureVectorAsObject, int>();
            MyMultiMap <FeatureVectorAsObject, int> hposContextToIndex = new MyMultiMap <FeatureVectorAsObject, int>();

            int n = corpus.featureVectors.Count;

            for (int i = 0; i < n; i++)
            {
                int[] features = corpus.featureVectors[i];
                wsContextToIndex.Map(new FeatureVectorAsObject(features, Trainer.FEATURES_INJECT_WS), i);
                hposContextToIndex.Map(new FeatureVectorAsObject(features, Trainer.FEATURES_HPOS), i);
            }

            int num_ambiguous_ws_vectors   = 0;
            int num_ambiguous_hpos_vectors = 0;

            // Dump output grouped by ws vs hpos then feature vector then category
            if (report)
            {
                Console.WriteLine(" --- INJECT WS ---");
            }
            IList <double> ws_entropies = new List <double>();

            foreach (FeatureVectorAsObject fo in wsContextToIndex.Keys)
            {
                var exemplarIndexes = wsContextToIndex[fo];

                // we have group by feature vector, now group by cat with that set for ws
                MyMultiMap <int, int> wsCatToIndexes = new MyMultiMap <int, int>();
                foreach (int i in exemplarIndexes)
                {
                    wsCatToIndexes.Map(corpus.injectWhitespace[i], i);
                }
                if (wsCatToIndexes.Count == 1)
                {
                    continue;
                }
                if (report)
                {
                    Console.WriteLine("Feature vector has " + exemplarIndexes.size() + " exemplars");
                }
                IList <int> catCounts = BuffUtils.map(wsCatToIndexes.Values, (x) => x.size());
                double      wsEntropy = Entropy.getNormalizedCategoryEntropy(Entropy.getCategoryRatios(catCounts));
                if (report)
                {
                    Console.Write("entropy={0,5:F4}\n", wsEntropy);
                }
                wsEntropy *= exemplarIndexes.size();
                ws_entropies.Add(wsEntropy);
                num_ambiguous_ws_vectors += exemplarIndexes.size();
                if (report)
                {
                    Console.Write(Trainer.featureNameHeader(Trainer.FEATURES_INJECT_WS));
                }

                if (report)
                {
                    foreach (int cat in wsCatToIndexes.Keys)
                    {
                        var indexes = wsCatToIndexes[cat];
                        foreach (int i in indexes)
                        {
                            string display = getExemplarDisplay(Trainer.FEATURES_INJECT_WS, corpus, corpus.injectWhitespace, i);
                            Console.WriteLine(display);
                        }
                        Console.WriteLine();
                    }
                }
            }

            if (report)
            {
                Console.WriteLine(" --- HPOS ---");
            }
            IList <double> hpos_entropies = new List <double>();

            foreach (FeatureVectorAsObject fo in hposContextToIndex.Keys)
            {
                MyHashSet <int> exemplarIndexes = hposContextToIndex[fo];

                // we have group by feature vector, now group by cat with that set for hpos
                MyMultiMap <int, int> hposCatToIndexes = new MyMultiMap <int, int>();
                foreach (int i in exemplarIndexes)
                {
                    hposCatToIndexes.Map(corpus.hpos[i], i);
                }
                if (hposCatToIndexes.Count == 1)
                {
                    continue;
                }
                if (report)
                {
                    Console.WriteLine("Feature vector has " + exemplarIndexes.size() + " exemplars");
                }
                IList <int> catCounts   = BuffUtils.map(hposCatToIndexes.Values, (x) => x.size());
                double      hposEntropy = Entropy.getNormalizedCategoryEntropy(Entropy.getCategoryRatios(catCounts));
                if (report)
                {
                    Console.Write("entropy={0,5:F4}\n", hposEntropy);
                }
                hposEntropy *= exemplarIndexes.size();
                hpos_entropies.Add(hposEntropy);
                num_ambiguous_hpos_vectors += exemplarIndexes.size();
                if (report)
                {
                    Console.Write(Trainer.featureNameHeader(Trainer.FEATURES_HPOS));
                }

                if (report)
                {
                    foreach (int cat in hposCatToIndexes.Keys)
                    {
                        var indexes = hposCatToIndexes[cat];
                        foreach (int?i in indexes)
                        {
                            string display = getExemplarDisplay(Trainer.FEATURES_HPOS, corpus, corpus.hpos, i.Value);
                            Console.WriteLine(display);
                        }
                        Console.WriteLine();
                    }
                }
            }
            Console.WriteLine();
            Console.WriteLine(language.name);
            Console.WriteLine("There are " + wsContextToIndex.Count + " unique ws feature vectors out of " + n + " = " + string.Format("{0,3:F1}%", 100.0 * wsContextToIndex.Count / n));
            Console.WriteLine("There are " + hposContextToIndex.Count + " unique hpos feature vectors out of " + n + " = " + string.Format("{0,3:F1}%", 100.0 * hposContextToIndex.Count / n));
            float prob_ws_ambiguous = num_ambiguous_ws_vectors / (float)n;

            Console.Write("num_ambiguous_ws_vectors   = {0,5:D}/{1,5:D} = {2,5:F3}\n", num_ambiguous_ws_vectors, n, prob_ws_ambiguous);
            float prob_hpos_ambiguous = num_ambiguous_hpos_vectors / (float)n;

            Console.Write("num_ambiguous_hpos_vectors = {0,5:D}/{1,5:D} = {2,5:F3}\n", num_ambiguous_hpos_vectors, n, prob_hpos_ambiguous);
            //		Collections.sort(ws_entropies);
            //		System.out.println("ws_entropies="+ws_entropies);
            Console.WriteLine("ws median,mean = " + BuffUtils.median(ws_entropies) + "," + BuffUtils.mean(ws_entropies));
            double expected_ws_entropy = (BuffUtils.sumDoubles(ws_entropies) / num_ambiguous_ws_vectors) * prob_ws_ambiguous;

            Console.WriteLine("expected_ws_entropy=" + expected_ws_entropy);

            Console.WriteLine("hpos median,mean = " + BuffUtils.median(hpos_entropies) + "," + BuffUtils.mean(hpos_entropies));
            double expected_hpos_entropy = (BuffUtils.sumDoubles(hpos_entropies) / num_ambiguous_hpos_vectors) * prob_hpos_ambiguous;

            Console.WriteLine("expected_hpos_entropy=" + expected_hpos_entropy);
        }
Exemple #27
0
        public static void Run()
        {
            Stopwatch sw = new Stopwatch();

            //Prepare MNIST data
            Console.WriteLine("MNIST Data Loading...");
            MnistData mnistData = new MnistData();

            //Writing the network configuration in FunctionStack
            FunctionStack nn = new FunctionStack(
                new Convolution2D(1, 32, 5, pad: 2, name: "l1 Conv2D", gpuEnable: true),
                new ReLU(name: "l1 ReLU"),
                //new AveragePooling (2, 2, name: "l1 AVGPooling"),
                new MaxPooling(2, 2, name: "l1 MaxPooling", gpuEnable: true),
                new Convolution2D(32, 64, 5, pad: 2, name: "l2 Conv2D", gpuEnable: true),
                new ReLU(name: "l2 ReLU"),
                //new AveragePooling (2, 2, name: "l2 AVGPooling"),
                new MaxPooling(2, 2, name: "l2 MaxPooling", gpuEnable: true),
                new Linear(13 * 13 * 64, 1024, name: "l3 Linear", gpuEnable: true),
                new ReLU(name: "l3 ReLU"),
                new Dropout(name: "l3 DropOut"),
                new Linear(1024, 10, name: "l4 Linear", gpuEnable: true)
                );

            //Declare optimizer
            nn.SetOptimizer(new Adam());

            Console.WriteLine("Training Start...");

            //Three generations learning
            for (int epoch = 1; epoch < 3; epoch++)
            {
                Console.WriteLine("epoch " + epoch);

                //Total error in the whole
                Real totalLoss      = 0;
                long totalLossCount = 0;

                //How many times to run the batch
                for (int i = 1; i < TRAIN_DATA_COUNT + 1; i++)
                {
                    sw.Restart();

                    Console.WriteLine("\nbatch count " + i + "/" + TRAIN_DATA_COUNT);

                    //Get data randomly from training data
                    TestDataSet datasetX = mnistData.GetRandomXSet(BATCH_DATA_COUNT);

                    //Execute batch learning in parallel
                    Real sumLoss = Trainer.Train(nn, datasetX.Data, datasetX.Label, new SoftmaxCrossEntropy());
                    totalLoss += sumLoss;
                    totalLossCount++;

                    //Result output
                    Console.WriteLine("total loss " + totalLoss / totalLossCount);
                    Console.WriteLine("local loss " + sumLoss);

                    sw.Stop();
                    Console.WriteLine("time" + sw.Elapsed.TotalMilliseconds);

                    //Test the accuracy if you move the batch 20 times
                    if (i % 20 == 0)
                    {
                        Console.WriteLine("\nTesting...");

                        //Get data randomly from test data
                        TestDataSet datasetY = mnistData.GetRandomYSet(TEACH_DATA_COUNT);

                        //Run test
                        Real accuracy = Trainer.Accuracy(nn, datasetY.Data, datasetY.Label);
                        Console.WriteLine("accuracy " + accuracy);
                    }
                }
            }
        }
        public void FullTrainToDescAndBack()
        {
            var tests = new[]
            {
                Tuple.Create(new[] { 1f, 0f, 0f }, new[] { 1f }),
                Tuple.Create(new[] { 0f, 0f, 0f }, new[] { 0f }),
                Tuple.Create(new[] { 1f, 1f, 0f }, new[] { 1f }),
                Tuple.Create(new[] { 1f, 0f, 1f }, new[] { 1f }),
                Tuple.Create(new[] { 1f, 1f, 1f }, new[] { 1f }),
                Tuple.Create(new[] { 0f, 1f, 0f }, new[] { 0f }),
                Tuple.Create(new[] { 0f, 1f, 1f }, new[] { 0f }),
                Tuple.Create(new[] { 0, 0f, 1f }, new[] { 0f })
            };

            var description = SimpleDescriptionBuilder.GetDescription(3, new[] { 3, 1 });
            var net         = Net.FromDescription(description);

            WeightFiller.FillWeights(net, 0.001f);

            var source = new CancellationTokenSource();
            var token  = source.Token;

            var trainer = new Trainer(tests, net);

            var firstError = trainer.Train(
                learnFactor: 0.5f,
                inertia: 0.2f,
                desiredError: 0.0001f,
                maxRuns: 50,
                progress: j => { },
                cancel: token);

            var desc2 = net.Description;
            var net2  = Net.FromDescription(desc2);

            var eval1 = net.GetEvaluationFunction();
            var eval2 = net2.GetEvaluationFunction();

            var avgError1 = 0d;
            var avgError2 = 0d;

            foreach (var test in tests)
            {
                var result1 = eval1(test.Item1);
                var result2 = eval2(test.Item1);
                avgError1 += Math.Pow(result1[0] - test.Item2[0], 2);
                avgError2 += Math.Pow(result2[0] - test.Item2[0], 2);
            }
            avgError2 /= tests.Length;

            Assert.IsTrue(avgError2 <= firstError);

            Func <float[], float[]> a = ((float[] inputs) =>
            {
                var in0 = inputs[0];
                var in1 = inputs[1];
                var in2 = inputs[2];
                var agg0 = (in0 * -2.458647) + (in1 * -0.07651551) + (in2 * -0.0518001) + -0.3729805;
                var out0 = Math.Log(1 + Math.Exp(agg0));
                var agg1 = (in0 * -2.523692) + (in1 * -0.05195593) + (in2 * -0.03320933) + -0.3351826;
                var out1 = Math.Log(1 + Math.Exp(agg1));
                var agg2 = (in0 * -2.458876) + (in1 * -0.07796045) + (in2 * -0.05187172) + -0.3720873;
                var out2 = Math.Log(1 + Math.Exp(agg2));
                var agg3 = (out0 * -0.8511373) + (out1 * -0.9345574) + (out2 * -0.8509701) + 4.971978;
                var out3 = Math.Log(1 + Math.Exp(agg3));
                return(new float[] { (float)out3 });
            });
        }
        public ActionResult MyProfile(Trainer c)
        {
            {
                var toBeUpdated = db.Trainers.Find(c.ID);
                toBeUpdated.Address = c.Address;
                toBeUpdated.Password = c.Password;
                toBeUpdated.Phone = c.Phone;
                db.Entry(toBeUpdated).CurrentValues.SetValues(toBeUpdated);
                db.SaveChanges();

                using (FitnessCenterEntities ff = new FitnessCenterEntities())
                {
                    User first = ff.Users.Find(int.Parse(Session["UserID"].ToString()));
                    first.Password = c.Password;
                    ff.Entry(first).CurrentValues.SetValues(first);
                    ff.SaveChanges();
                }
                return RedirectToAction("MyProfile", "Trainer");
            }
        }
 public bool generalInfo(Trainer info)
 {
     trainer = info;
     return(true);
 }
Exemple #31
0
        /// <summary>
        /// TrainAndEvaluateWithAnimalData shows how to do transfer learning without using a MinibatchSource.
        /// Training and evaluation data are prepared as appropriate in the code.
        /// Batching is done explicitly in the code as well.
        /// Because the amount of animal data is limited, it is fine to work this way.
        /// In real scenarios, it is recommended to code efficiently for data preprocessing and batching,
        /// probably with parallelization and streaming as what has been done in MinibatchSource.
        /// </summary>
        /// <param name="device">CPU or GPU device to run</param>
        /// <param name="forceRetrain">Force to train the model if true. If false,
        /// it only evaluates the model is it exists. </param>
        public static void TrainAndEvaluateWithAnimalData(DeviceDescriptor device, bool forceRetrain = false)
        {
            string animalDataFolder = Path.Combine(ExampleImageFoler, "Animals");

            string[] animals = new string[] { "Sheep", "Wolf" };
            int      animalModelNumClasses = 2;
            string   animalsModelFile      = Path.Combine(CurrentFolder, "AnimalsTransferLearning.model");

            // If the model exists and it is not set to force retrain, validate the model and return.
            if (File.Exists(animalsModelFile) && !forceRetrain)
            {
                ValidateModelWithoutMinibatchSource(animalsModelFile, Path.Combine(animalDataFolder, "Test"), animals,
                                                    imageDims, animalModelNumClasses, device);
                return;
            }

            List <Tuple <string, int, float[]> > trainingDataMap =
                PrepareTrainingDataFromSubfolders(Path.Combine(animalDataFolder, "Train"), animals, imageDims);

            // prepare the transfer model
            string   predictionNodeName = "prediction";
            Variable imageInput, labelInput;
            Function trainingLoss, predictionError;
            Function transferLearningModel = CreateTransferLearningModel(Path.Combine(ExampleImageFoler, BaseResnetModelFile), featureNodeName, predictionNodeName,
                                                                         lastHiddenNodeName, animalModelNumClasses, device,
                                                                         out imageInput, out labelInput, out trainingLoss, out predictionError);

            // prepare for training
            int   numMinibatches               = 5;
            float learningRatePerMinibatch     = 0.2F;
            float learningmomentumPerMinibatch = 0.9F;
            float l2RegularizationWeight       = 0.1F;

            AdditionalLearningOptions additionalLearningOptions =
                new AdditionalLearningOptions()
            {
                l2RegularizationWeight = l2RegularizationWeight
            };
            IList <Learner> parameterLearners = new List <Learner>()
            {
                Learner.MomentumSGDLearner(transferLearningModel.Parameters(),
                                           new TrainingParameterScheduleDouble(learningRatePerMinibatch, 0),
                                           new TrainingParameterScheduleDouble(learningmomentumPerMinibatch, 0),
                                           true,
                                           additionalLearningOptions)
            };
            var trainer = Trainer.CreateTrainer(transferLearningModel, trainingLoss, predictionError, parameterLearners);

            // train the model
            for (int minibatchCount = 0; minibatchCount < numMinibatches; ++minibatchCount)
            {
                Value imageBatch, labelBatch;
                int   batchCount = 0, batchSize = 15;
                while (GetImageAndLabelMinibatch(trainingDataMap, batchSize, batchCount++,
                                                 imageDims, animalModelNumClasses, device, out imageBatch, out labelBatch))
                {
                    //TODO: sweepEnd should be set properly.
#pragma warning disable 618
                    trainer.TrainMinibatch(new Dictionary <Variable, Value>()
                    {
                        { imageInput, imageBatch },
                        { labelInput, labelBatch }
                    }, device);
#pragma warning restore 618
                    TestHelper.PrintTrainingProgress(trainer, minibatchCount, 1);
                }
            }

            // save the trained model
            transferLearningModel.Save(animalsModelFile);

            // done with training, continue with validation
            double error = ValidateModelWithoutMinibatchSource(animalsModelFile, Path.Combine(animalDataFolder, "Test"), animals,
                                                               imageDims, animalModelNumClasses, device);
            Console.WriteLine(error);
        }
Exemple #32
0
        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            Trainer trainer = (Trainer)TrainerPathComboBox.SelectedItem;
            bool    force   = mode == Mode.COMPLETE || ForceCheckBox.IsChecked.Value;

            if (!File.Exists(trainer.Path))
            {
                MessageTools.Warning("file does not exist '" + trainer.Path + "'");
                return;
            }

            string database = DatabaseHandler.DatabaseName;

            DatabaseStream stream = (DatabaseStream)StreamsBox.SelectedItem;

            string sessionList = "";
            var    sessions    = SessionsBox.SelectedItems;

            foreach (DatabaseSession session in sessions)
            {
                if (sessionList == "")
                {
                    sessionList += session.Name;
                }
                else
                {
                    sessionList += ";" + session.Name;
                }
            }

            DatabaseScheme scheme = (DatabaseScheme)SchemesBox.SelectedItem;

            string rolesList = "";
            var    roles     = RolesBox.SelectedItems;

            foreach (DatabaseRole role in roles)
            {
                if (rolesList == "")
                {
                    rolesList += role.Name;
                }
                else
                {
                    rolesList += ";" + role.Name;
                }
            }

            DatabaseAnnotator annotator = (DatabaseAnnotator)AnnotatorsBox.SelectedItem;

            string trainerLeftContext  = LeftContextTextBox.Text;
            string trainerRightContext = RightContextTextBox.Text;
            string trainerBalance      = ((ComboBoxItem)BalanceComboBox.SelectedItem).Content.ToString();

            logTextBox.Text = "";

            if (mode == Mode.TRAIN ||
                mode == Mode.COMPLETE)
            {
                string   streamName  = "";
                string[] streamParts = stream.Name.Split('.');
                if (streamParts.Length <= 1)
                {
                    streamName = stream.Name;
                }
                else
                {
                    streamName = streamParts[1];
                    for (int i = 2; i < streamParts.Length; i++)
                    {
                        streamName += "." + streamParts[i];
                    }
                }


                string trainerDir = Properties.Settings.Default.CMLDirectory + "\\" +
                                    Defaults.CML.ModelsFolderName + "\\" +
                                    Defaults.CML.ModelsTrainerFolderName + "\\" +
                                    scheme.Type.ToString().ToLower() + "\\" +
                                    scheme.Name + "\\" +
                                    stream.Type + "{" +
                                    streamName + "}\\" +
                                    trainer.Name + "\\";

                Directory.CreateDirectory(trainerDir);

                string trainerName    = TrainerNameTextBox.Text == "" ? trainer.Name : TrainerNameTextBox.Text;
                string trainerOutPath = mode == Mode.COMPLETE ? tempTrainerPath : trainerDir + trainerName;

                if (force || !File.Exists(trainerOutPath + ".trainer"))
                {
                    try
                    {
                        logTextBox.Text += handler.CMLTrainModel(trainer.Path,
                                                                 trainerOutPath,
                                                                 Properties.Settings.Default.DatabaseDirectory,
                                                                 Properties.Settings.Default.DatabaseAddress,
                                                                 Properties.Settings.Default.MongoDBUser,
                                                                 MainHandler.Decode(Properties.Settings.Default.MongoDBPass),
                                                                 database,
                                                                 sessionList,
                                                                 scheme.Name,
                                                                 rolesList,
                                                                 annotator.Name,
                                                                 stream.Name,
                                                                 trainerLeftContext,
                                                                 trainerRightContext,
                                                                 trainerBalance,
                                                                 mode == Mode.COMPLETE);
                    }

                    catch (Exception ex)
                    {
                        logTextBox.Text += ex;
                    }
                }
                else
                {
                    logTextBox.Text += "skip " + trainerOutPath + "\n";
                }
            }

            if (mode == Mode.PREDICT ||
                mode == Mode.COMPLETE)
            {
                if (true || force)
                {
                    double confidence = -1.0;
                    if (ConfidenceCheckBox.IsChecked == true && ConfidenceTextBox.IsEnabled)
                    {
                        double.TryParse(ConfidenceTextBox.Text, out confidence);
                        Properties.Settings.Default.CMLDefaultConf = confidence;
                    }
                    double minGap = 0.0;
                    if (FillGapCheckBox.IsChecked == true && FillGapTextBox.IsEnabled)
                    {
                        double.TryParse(FillGapTextBox.Text, out minGap);
                        Properties.Settings.Default.CMLDefaultGap = minGap;
                    }
                    double minDur = 0.0;
                    if (RemoveLabelCheckBox.IsChecked == true && RemoveLabelTextBox.IsEnabled)
                    {
                        double.TryParse(RemoveLabelTextBox.Text, out minDur);
                        Properties.Settings.Default.CMLDefaultMinDur = minDur;
                    }
                    Properties.Settings.Default.Save();

                    try
                    {
                        logTextBox.Text += handler.CMLPredictAnnos(mode == Mode.COMPLETE ? tempTrainerPath : trainer.Path,
                                                                   Properties.Settings.Default.DatabaseDirectory,
                                                                   Properties.Settings.Default.DatabaseAddress,
                                                                   Properties.Settings.Default.MongoDBUser,
                                                                   MainHandler.Decode(Properties.Settings.Default.MongoDBPass),
                                                                   database,
                                                                   sessionList,
                                                                   scheme.Name,
                                                                   rolesList,
                                                                   annotator.Name,
                                                                   stream.Name,
                                                                   trainerLeftContext,
                                                                   trainerRightContext,
                                                                   confidence,
                                                                   minGap,
                                                                   minDur,
                                                                   mode == Mode.COMPLETE);
                    }

                    catch (Exception ex)
                    {
                        logTextBox.Text += ex;
                    }
                }
            }

            if (mode == Mode.EVALUATE)
            {
                string evalOutPath = Properties.Settings.Default.CMLDirectory + "\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                try

                {
                    logTextBox.Text += handler.CMLEvaluateModel(evalOutPath,
                                                                trainer.Path,
                                                                Properties.Settings.Default.DatabaseDirectory,
                                                                Properties.Settings.Default.DatabaseAddress,
                                                                Properties.Settings.Default.MongoDBUser,
                                                                MainHandler.Decode(Properties.Settings.Default.MongoDBPass),
                                                                database,
                                                                sessionList,
                                                                scheme.Name,
                                                                rolesList,
                                                                annotator.Name,
                                                                stream.Name,
                                                                LosoCheckBox.IsChecked.Value);

                    if (File.Exists(evalOutPath))
                    {
                        ConfmatWindow confmat = new ConfmatWindow(evalOutPath);
                        confmat.ShowDialog();
                        File.Delete(evalOutPath);
                    }
                }

                catch (Exception ex)
                {
                    logTextBox.Text += ex;
                }
            }

            if (mode == Mode.COMPLETE)
            {
                handler.ReloadAnnoTierFromDatabase(AnnoTierStatic.Selected, false);

                var dir = new DirectoryInfo(Path.GetDirectoryName(tempTrainerPath));
                foreach (var file in dir.EnumerateFiles(Path.GetFileName(tempTrainerPath) + "*"))
                {
                    file.Delete();
                }

                Close();
            }
        }
Exemple #33
0
 public TrainerResponse(bool success, string message, Trainer trainer) : base(success, message)
 {
     Trainer = trainer;
 }
Exemple #34
0
 public TrainerResponse(Trainer trainer) : this(true, string.Empty, trainer)
 {
 }
        public void Run()
        {
            // Prepare data
            var baseDataDirectoryPath = @"E:\DataSets\Mnist";
            var trainFilePath         = Path.Combine(baseDataDirectoryPath, "Train-28x28_cntk_text.txt");
            var testFilePath          = Path.Combine(baseDataDirectoryPath, "Test-28x28_cntk_text.txt");

            // Define the input and output shape.
            var inputShape      = new int[] { 28, 28, 1 };
            var numberOfClasses = 10;
            var outputShape     = new int[] { numberOfClasses };

            // Define data type and device for the model.
            var dataType = DataType.Float;
            var device   = DeviceDescriptor.UseDefaultDevice();

            // Setup initializers
            var random = new Random(232);
            Func <CNTKDictionary> weightInit = () => Initializers.GlorotNormal(random.Next());
            var biasInit = Initializers.Zero();

            // Ensure reproducible results with CNTK.
            CNTKLib.SetFixedRandomSeed((uint)random.Next());
            CNTKLib.ForceDeterministicAlgorithms();

            // Create the architecture.
            var input = Layers.Input(inputShape, dataType);
            // scale input between 0 and 1.
            var scaledInput = CNTKLib.ElementTimes(Constant.Scalar(0.00390625f, device), input);

            var network = scaledInput
                          .Conv2D((3, 3), 32, (1, 1), Padding.None, weightInit(), biasInit, device, dataType)
                          .ReLU()
                          .MaxPool2D((2, 2), (2, 2), Padding.None)

                          .Conv2D((3, 3), 32, (1, 1), Padding.None, weightInit(), biasInit, device, dataType)
                          .ReLU()
                          .MaxPool2D((2, 2), (2, 2), Padding.None)

                          .Conv2D((3, 3), 32, (1, 1), Padding.None, weightInit(), biasInit, device, dataType)
                          .ReLU()

                          .Dense(64, weightInit(), biasInit, device, dataType)
                          .ReLU()
                          .Dense(numberOfClasses, weightInit(), biasInit, device, dataType)
                          .Softmax();

            // Get input and target variables from network.
            var inputVariable  = network.Arguments[0];
            var targetVariable = Variable.InputVariable(outputShape, dataType);

            // setup loss and learner.
            var lossFunc   = Losses.CategoricalCrossEntropy(network.Output, targetVariable);
            var metricFunc = Metrics.Accuracy(network.Output, targetVariable);

            // setup trainer.
            var learner = Learners.RMSProp(network.Parameters());
            var trainer = Trainer.CreateTrainer(network, lossFunc, metricFunc, new List <Learner> {
                learner
            });

            // Create the network.
            var model = new Model(trainer, network, dataType, device);

            // Write model summary.
            Trace.WriteLine(model.Summary());

            // Setup minibatch sources.
            // Network will be trained using the training set,
            // and tested using the test set.

            // setup name to variable map.
            var nameToVariable = new Dictionary <string, Variable>
            {
                { "features", inputVariable },
                { "labels", targetVariable },
            };

            // The order of the training data is randomize.
            var train          = CreateMinibatchSource(trainFilePath, nameToVariable, randomize: true);
            var trainingSource = new CntkMinibatchSource(train, nameToVariable);

            // Notice randomization is switched off for test data.
            var test       = CreateMinibatchSource(testFilePath, nameToVariable, randomize: false);
            var testSource = new CntkMinibatchSource(test, nameToVariable);

            // Train the model using the training set.
            model.Fit(trainingSource, epochs: 5, batchSize: 64);

            // Evaluate the model using the test set.
            var(loss, metric) = model.Evaluate(testSource);

            // Write the test set loss and metric to debug output.
            Trace.WriteLine($"Test set - Loss: {loss}, Metric: {metric}");
        }
Exemple #36
0
        static void Main(string[] args)
        {
            Admin stefan = new Admin("Stefan", "Sibinovski", 1111);
            Admin tomas  = new Admin("Tomas", "Neznam", 2222);

            List <Admin> allAdmins = new List <Admin> {
                stefan, tomas
            };


            Student        john        = new Student("John", "Doe", 1234);
            Student        mario       = new Student("Mario", "Simonovski", 1233);
            List <Student> allStudents = new List <Student>()
            {
                john, mario
            };

            Subjects math    = new Subjects("Math", 5);
            Subjects art     = new Subjects("Art", 3);
            Subjects biology = new Subjects("Biology", 3);
            Subjects sport   = new Subjects("Sport", 3);
            Subjects music   = new Subjects("Music", 2);

            List <Subjects> allSubjects = new List <Subjects>()
            {
                math, art, biology, sport, music
            };

            Trainer        ivan        = new Trainer("Ivan", "Petrovski", 1234);
            Trainer        milodrag    = new Trainer("Milodrag", "Milkovski", 1233);
            List <Trainer> allTrainers = new List <Trainer>()
            {
                ivan, milodrag
            };

            var JohnStudent = (from student in allStudents
                               where student.FristName == "John"
                               select student).FirstOrDefault();

            JohnStudent.AddSubAndGrades(allSubjects[0], 2);
            JohnStudent.AddSubAndGrades(allSubjects[2], 4);
            JohnStudent.AddSubAndGrades(allSubjects[1], 2);
            JohnStudent.AddSubAndGrades(allSubjects[3], 4);



            var marioStudent = (from student in allStudents
                                where student.FristName == "Mario"
                                select student).FirstOrDefault();

            marioStudent.AddSubAndGrades(allSubjects[0], 5);
            marioStudent.AddSubAndGrades(allSubjects[4], 2);

            Console.WriteLine("Enter a number ");
            Console.WriteLine(" 1:Admin \n 2:Trainer \n 3:Student");

            var input = int.Parse(Console.ReadLine());

            if (input == 1)
            {
                Console.WriteLine("Please login.");
                Console.WriteLine("please enter username");
                var inputUsername = Console.ReadLine();

                Console.WriteLine("please enter password");
                int  inputPassword;
                bool inputAdmin2 = Int32.TryParse(Console.ReadLine(), out inputPassword);

                var result = (from admin in allAdmins
                              where admin.FristName == inputUsername && admin.Password == inputPassword
                              select admin).FirstOrDefault();

                Admin admince = new Admin();

                admince = result;
                Console.WriteLine("Hello " + admince.GetFullName());
                Console.WriteLine("1:Add \n 2:Remove");

                int  inputAddRemove;
                bool inputAdmin4 = Int32.TryParse(Console.ReadLine(), out inputAddRemove);

                if (inputAddRemove == 1) //add
                {
                    Console.WriteLine("1:Student 2:Trainer 3: Admin! choose 1 to add");
                    var inputPerson = int.Parse(Console.ReadLine());

                    if (inputPerson == 1) //add student
                    {
                        AddStudent(allStudents);
                    }
                    else if (inputPerson == 2) //add trainer
                    {
                        AddTrainer(allTrainers);
                    }
                    else if (inputPerson == 3) //add admin
                    {
                        AddAdmin(allAdmins);
                    }
                    else
                    {
                        Console.WriteLine("pls enter num");
                    }
                }

                else if (inputAddRemove == 2)
                {
                    Console.WriteLine("1:Student 2:Trainer 3:Admin  choose 1 to remove");
                    var inputPersonRemove = int.Parse(Console.ReadLine());
                    if (inputPersonRemove == 1)
                    {
                        admince.SeeAllStudent(allStudents);

                        admince.RemoveStudent(allStudents);

                        //  allStudents.RemoveAll(emp => emp.FristName == inputRemoveStudent);
                    }
                    else if (inputPersonRemove == 2)
                    {
                        admince.SeeallTrainers(allTrainers);
                        admince.RemoveTrainer(allTrainers);

                        //  allTrainers.RemoveAll(emp => emp.FristName == inputRemoveTrainer);
                    }
                    else if (inputPersonRemove == 3)
                    {
                        admince.SeeAllAdmins(allAdmins);

                        Console.WriteLine("type the name of the admin to delete it ");
                        string adminName = Console.ReadLine();
                        Console.WriteLine("type the lastname of the admin to delete it ");
                        string adminLastName = Console.ReadLine();

                        foreach (var admin in allAdmins)
                        {
                            if (admince.FristName.Equals(adminName))
                            {
                                Console.WriteLine("you cant remove yourself");
                                break;
                            }
                            else if (admin.FristName.Equals(adminName) && admin.LastName.Equals(adminLastName))
                            {
                                allAdmins.Remove(admin);
                                break;
                            }
                        }
                    }

                    else
                    {
                        Console.WriteLine("pls enter number");
                    }
                }
            }
            else if (input == 2)  //Trainer
            {
                Console.WriteLine("Please login.");
                Console.WriteLine("please enter username");
                var inputTrainerUser = Console.ReadLine();

                Console.WriteLine("please enter password");
                int inputTrainerPassword = int.Parse(Console.ReadLine());

                var trainer = (from trainer1 in allTrainers
                               where trainer1.FristName == inputTrainerUser || trainer1.Password == inputTrainerPassword
                               select trainer1).FirstOrDefault();

                Trainer trainer2 = new Trainer();
                trainer2 = trainer;
                Console.WriteLine("Hello " + trainer.GetFullName());
                Console.WriteLine("1:all students 2:all subjects");

                int inputStudentSubject = int.Parse(Console.ReadLine());

                if (inputStudentSubject == 1)
                {
                    Console.WriteLine("enter a name to get his subjects");

                    trainer2.SeeAllStudent(allStudents);

                    string frist = Console.ReadLine();

                    foreach (var item in allStudents)
                    {
                        if (item.FristName.Equals(frist))
                        {
                            foreach (var sub in allSubjects)
                            {
                                Console.WriteLine($"{sub.SubjectName} ");
                            }
                        }
                    }
                }
                else if (inputStudentSubject == 2)
                {
                    foreach (var subject in allSubjects)
                    {
                        Console.WriteLine(subject.SubjectName);
                    }
                }
            }
            else if (input == 3) //student
            {
                Console.WriteLine("Please login.");
                Console.WriteLine("please enter username");
                var inputStudentUser = Console.ReadLine();

                Console.WriteLine("please enter password");
                var inputStudentPw = int.Parse(Console.ReadLine());

                var loginStudent = (from student in allStudents
                                    where student.FristName == inputStudentUser && student.Password == inputStudentPw
                                    select student).FirstOrDefault();
                Student studence = new Student();
                studence = loginStudent;


                Console.WriteLine("Hello " + studence.GetFullName());
                bool c = true;
                studence.SeeSubject(inputStudentUser, allStudents, c);
            }

            Console.ReadLine();
        }
Exemple #37
0
        public Trainer GetTrainerByEmail(string email)
        {
            Trainer trainer = InMemoryDatabase.Trainers.FirstOrDefault(trainer => trainer.Email == email);

            return(trainer);
        }
Exemple #38
0
 public override void OnTrainingStarted(Trainer trainer, int epoches)
 {
     //Trainer = trainer;
 }
 public static Color GetByName(string colourName)
 {
     return(Trainer.HexToColor(Colours[colourName].Substring(1)));
 }
        private void GetTrainers()
        {
            if (RolesBox.SelectedItem == null || AnnotatorsBox.SelectedItem == null || SchemesBox.SelectedItem == null)
            {
                return;
            }

            TrainerPathComboBox.ItemsSource = null;

            if (StreamsBox.SelectedItem != null)
            {
                DatabaseStream stream = (DatabaseStream)StreamsBox.SelectedItem;
                DatabaseScheme scheme = (DatabaseScheme)SchemesBox.SelectedItem;

                if (scheme != null)
                {
                    bool isDiscrete = scheme.Type == AnnoScheme.TYPE.DISCRETE;

                    FillGapCheckBox.IsEnabled     = isDiscrete;
                    FillGapTextBox.IsEnabled      = isDiscrete;
                    RemoveLabelCheckBox.IsEnabled = isDiscrete;
                    RemoveLabelTextBox.IsEnabled  = isDiscrete;

                    bool template = mode == Mode.TRAIN || mode == Mode.COMPLETE;

                    List <Trainer> trainers = getTrainer(stream, scheme, template);
                    if (trainers.Count > 0)
                    {
                        TrainerPathComboBox.ItemsSource = trainers;
                    }
                }
            }

            if (TrainerPathComboBox.Items.Count > 0)
            {
                Trainer trainer = ((List <Trainer>)TrainerPathComboBox.ItemsSource).Find(t => t.Name == Properties.Settings.Default.CMLDefaultTrainer);

                if (trainer != null)
                {
                    TrainerPathComboBox.SelectedItem = trainer;
                }
                else
                {
                    TrainerPathComboBox.SelectedIndex = 0;
                }
            }

            if (TrainerPathComboBox.SelectedItem != null)
            {
                Trainer trainer = (Trainer)TrainerPathComboBox.SelectedItem;

                LeftContextTextBox.Text  = trainer.LeftContext;
                RightContextTextBox.Text = trainer.RightContext;

                BalanceComboBox.SelectedIndex = 0;
                if (trainer.Balance.ToLower() == "under")
                {
                    BalanceComboBox.SelectedIndex = 1;
                }
                else if (trainer.Balance.ToLower() == "over")
                {
                    BalanceComboBox.SelectedIndex = 2;
                }
                string database = "";
                if (DatabasesBox.SelectedItem != null)
                {
                    database = DatabasesBox.SelectedItem.ToString();
                }
                TrainerNameTextBox.Text = mode == Mode.COMPLETE ? Path.GetFileName(tempTrainerPath) : database;

                TrainerPathLabel.Content = trainer.Path;
            }
        }
Exemple #41
0
        public Dictionary <string, List <double> > Train(object trainData, object validationData, int epoches, int batchSize, On_Epoch_Start OnEpochStart, On_Epoch_End OnEpochEnd, On_Batch_Start onBatchStart, On_Batch_End OnBatchEnd)
        {
            ImageDataGenerator train      = (ImageDataGenerator)trainData;
            ImageDataGenerator validation = validationData != null ? (ImageDataGenerator)validationData : null;
            Dictionary <string, List <double> > result = new Dictionary <string, List <double> >();
            var trainer      = Trainer.CreateTrainer(Model, lossFunc, metricFunc, learners);
            int currentEpoch = 1;
            Dictionary <string, double> metricsList = new Dictionary <string, double>();
            int imageSize  = featureVariable.Shape.Rank == 1 ? featureVariable.Shape[0] : featureVariable.Shape[0] * featureVariable.Shape[1] * featureVariable.Shape[2];
            int numClasses = labelVariable.Shape[0];
            IList <StreamConfiguration> streamConfigurations = new StreamConfiguration[] { new StreamConfiguration("features", imageSize), new StreamConfiguration("labels", numClasses) };

            if (train.GenType == ImageGenType.FromTextFile)
            {
                train.LoadTextData(featureVariable, labelVariable);
                if (validation != null)
                {
                    validation.LoadTextData(featureVariable, labelVariable);
                }
            }

            while (currentEpoch <= epoches)
            {
                metricsList.Clear();
                OnEpochStart(currentEpoch);
                int miniBatchCount = 1;
                while (!train.NextBatch(batchSize))
                {
                    onBatchStart(currentEpoch, miniBatchCount);
                    trainer.TrainMinibatch(new Dictionary <Variable, Value> {
                        { featureVariable, train.CurrentBatchX }, { labelVariable, train.CurrentBatchY }
                    }, GlobalParameters.Device);
                    OnBatchEnd(currentEpoch, miniBatchCount, trainer.TotalNumberOfSamplesSeen(), trainer.PreviousMinibatchLossAverage(), new Dictionary <string, double>()
                    {
                        { metricName, trainer.PreviousMinibatchEvaluationAverage() }
                    });

                    miniBatchCount++;
                }

                if (!result.ContainsKey("loss"))
                {
                    result.Add("loss", new List <double>());
                }

                if (!result.ContainsKey(metricName))
                {
                    result.Add(metricName, new List <double>());
                }

                double lossValue   = trainer.PreviousMinibatchLossAverage();
                double metricValue = trainer.PreviousMinibatchEvaluationAverage();
                result["loss"].Add(lossValue);
                result[metricName].Add(metricValue);
                metricsList.Add(metricName, metricValue);
                if (validation != null)
                {
                    if (!result.ContainsKey("val_loss"))
                    {
                        result.Add("val_loss", new List <double>());
                    }

                    if (!result.ContainsKey("val_" + metricName))
                    {
                        result.Add("val_" + metricName, new List <double>());
                    }

                    List <double> totalEvalBatchLossList   = new List <double>();
                    List <double> totalEvalMetricValueList = new List <double>();
                    while (validation.NextBatch(batchSize))
                    {
                        Variable actualVariable = CNTKLib.InputVariable(labelVariable.Shape, DataType.Float);
                        var      evalLossFunc   = Losses.Get(lossName, labelVariable, actualVariable);
                        var      evalMetricFunc = Metrics.Get(metricName, labelVariable, actualVariable);
                        Value    actual         = EvaluateInternal(validation.CurrentBatchX);
                        Value    expected       = validation.CurrentBatchY;
                        var      inputDataMap   = new Dictionary <Variable, Value>()
                        {
                            { labelVariable, expected }, { actualVariable, actual }
                        };
                        var outputDataMap = new Dictionary <Variable, Value>()
                        {
                            { evalLossFunc.Output, null }
                        };

                        evalLossFunc.Evaluate(inputDataMap, outputDataMap, GlobalParameters.Device);
                        var evalLoss = outputDataMap[evalLossFunc.Output].GetDenseData <float>(evalLossFunc.Output).Select(x => x.First()).ToList();
                        totalEvalBatchLossList.Add(evalLoss.Average());

                        inputDataMap = new Dictionary <Variable, Value>()
                        {
                            { labelVariable, expected }, { actualVariable, actual }
                        };
                        outputDataMap = new Dictionary <Variable, Value>()
                        {
                            { evalMetricFunc.Output, null }
                        };
                        evalMetricFunc.Evaluate(inputDataMap, outputDataMap, GlobalParameters.Device);
                        var evalMetric = outputDataMap[evalMetricFunc.Output].GetDenseData <float>(evalMetricFunc.Output).Select(x => x.First()).ToList();
                        totalEvalMetricValueList.Add(evalMetric.Average());
                    }

                    result["val_loss"].Add(totalEvalBatchLossList.Average());
                    metricsList.Add("val_loss", totalEvalBatchLossList.Average());
                    result["val_" + metricName].Add(totalEvalMetricValueList.Average());
                    metricsList.Add("val_" + metricName, totalEvalMetricValueList.Average());
                }

                OnEpochEnd(currentEpoch, trainer.TotalNumberOfSamplesSeen(), lossValue, metricsList);
                currentEpoch++;
            }

            return(result);
        }
Exemple #42
0
        public static void Run()
        {
            //Describe each initial value
            Real[,,,] initial_W1 =
            {
                { { { 1.0,  0.5, 0.0 }, {  0.5, 0.0, -0.5 }, { 0.0, -0.5, -1.0 } } },
                { { { 0.0, -0.1, 0.1 }, { -0.3, 0.4,  0.7 }, { 0.5, -0.2,  0.2 } } }
            };
            Real[] initial_b1 = { 0.5, 1.0 };

            Real[,,,] initial_W2 =
            {
                { { { -0.1,  0.6 }, { 0.3, -0.9 } }, { {  0.7, 0.9 }, { -0.2, -0.3 } } },
                { { { -0.6, -0.1 }, { 0.3,  0.3 } }, { { -0.5, 0.8 }, {  0.9,  0.1 } } }
            };
            Real[] initial_b2 = { 0.1, 0.9 };

            Real[,] initial_W3 =
            {
                { 0.5, 0.3, 0.4, 0.2, 0.6, 0.1, 0.4, 0.3 },
                { 0.6, 0.4, 0.9, 0.1, 0.5, 0.2, 0.3, 0.4 }
            };
            Real[] initial_b3 = { 0.01, 0.02 };

            Real[,] initial_W4 = { { 0.8, 0.2 }, { 0.4, 0.6 } };
            Real[] initial_b4 = { 0.02, 0.01 };


            //Input data
            NdArray x = new NdArray(new Real[, , ] {
                {
                    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.9, 0.2, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.2, 0.8, 0.9, 0.1, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.1, 0.8, 0.5, 0.8, 0.1, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.3, 0.3, 0.1, 0.7, 0.2, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.1, 0.0, 0.1, 0.7, 0.2, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.1, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.4, 0.8, 0.1, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.8, 0.4, 0.1, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.2, 0.8, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.1, 0.8, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0 },
                    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }
                }
            });

            //Teacher signal
            Real[] t = { 0.0, 1.0 };


            //If you want to check the contents of a layer, have an instance as a single layer
            Convolution2D l2 = new Convolution2D(1, 2, 3, initialW: initial_W1, initialb: initial_b1, name: "l2 Conv2D");

            //Writing the network configuration in FunctionStack
            FunctionStack nn = new FunctionStack(
                l2, //new Convolution 2 D (1, 2, 3, initial W: initial W 1, initial b: initial _ b 1),
                new ReLU(name: "l2 ReLU"),
                //new AveragePooling (2, 2, name: "l2 AVGPooling"),
                new MaxPooling(2, 2, name: "l2 MaxPooling"),
                new Convolution2D(2, 2, 2, initialW: initial_W2, initialb: initial_b2, name: "l3 Conv2D"),
                new ReLU(name: "l3 ReLU"),
                //new AveragePooling (2, 2, name: "l3 AVGPooling"),
                new MaxPooling(2, 2, name: "l3 MaxPooling"),
                new Linear(8, 2, initialW: initial_W3, initialb: initial_b3, name: "l4 Linear"),
                new ReLU(name: "l4 ReLU"),
                new Linear(2, 2, initialW: initial_W4, initialb: initial_b4, name: "l5 Linear")
                );

            //If you omit the optimizer declaration, the default SGD (0.1) is used
            nn.SetOptimizer(new SGD());

            //Training conducted
            Trainer.Train(nn, x, t, new MeanSquaredError(), false);

            //When updating is executed grad will be consumed, so output the value first
            Console.WriteLine("gw1");
            Console.WriteLine(l2.Weight.ToString("Grad"));

            Console.WriteLine("gb1");
            Console.WriteLine(l2.Bias.ToString("Grad"));

            //update
            nn.Update();

            Console.WriteLine("w1");
            Console.WriteLine(l2.Weight);

            Console.WriteLine("b1");
            Console.WriteLine(l2.Bias);
        }
Exemple #43
0
        public static void Run()
        {
            //訓練回数
            const int learningCount = 10000;

            //訓練データ
            Real[][] trainData =
            {
                new Real[] { 0, 0 },
                new Real[] { 1, 0 },
                new Real[] { 0, 1 },
                new Real[] { 1, 1 }
            };

            //訓練データラベル
            Real[][] trainLabel =
            {
                new Real[] { 0 },
                new Real[] { 1 },
                new Real[] { 1 },
                new Real[] { 0 }
            };

            //ネットワークの構成は FunctionStack に書き連ねる
            FunctionStack nn = new FunctionStack(
                new Linear(2, 2, name: "l1 Linear"),
                new Sigmoid(name: "l1 Sigmoid"),
                new Linear(2, 2, name: "l2 Linear")
                );

            //optimizerを宣言
            nn.SetOptimizer(new MomentumSGD());

            //訓練ループ
            Console.WriteLine("Training...");
            for (int i = 0; i < learningCount; i++)
            {
                for (int j = 0; j < trainData.Length; j++)
                {
                    //訓練実行時にロス関数を記述
                    Trainer.Train(nn, trainData[j], trainLabel[j], new SoftmaxCrossEntropy());
                }
            }

            //訓練結果を表示
            Console.WriteLine("Test Start...");
            foreach (Real[] input in trainData)
            {
                NdArray result      = nn.Predict(input)[0];
                int     resultIndex = Array.IndexOf(result.Data, result.Data.Max());
                Console.WriteLine(input[0] + " xor " + input[1] + " = " + resultIndex + " " + result);
            }

            //学習の終わったネットワークを保存
            ModelIO.Save(nn, "test.nn");

            //学習の終わったネットワークを読み込み
            FunctionStack testnn = ModelIO.Load("test.nn");

            Console.WriteLine("Test Start...");
            foreach (Real[] input in trainData)
            {
                NdArray result      = testnn.Predict(input)[0];
                int     resultIndex = Array.IndexOf(result.Data, result.Data.Max());
                Console.WriteLine(input[0] + " xor " + input[1] + " = " + resultIndex + " " + result);
            }
        }
    public void ApplyTrainingModifierEffectsTarget(Trainer trainer, MiniGameBase minigame) {
        int currentGen = trainer.PlayingCurGeneration; // + trainer.PlayerList[0].masterPopulation.trainingGenerations;
        if (trainer.loadedTrainingSave != null) {
            currentGen += trainer.loadedTrainingSave.endGeneration;
        }
        int numModifiers = activeTrainingModifierList.Count;
        int numRounds = 0;
        int gameRoundIndex = 0;

        // v v v SUPER HACKY!!! v v v 
        MiniGameCritterWalkBasic game = (MiniGameCritterWalkBasic)minigame;
        // Clear existing Lists:
        if (game.targetPositionList == null) {
            game.targetPositionList = new List<Vector3>();
        }
        else {
            game.targetPositionList.Clear();
        }
        if (game.endGameTimesList == null) {
            game.endGameTimesList = new List<int>();
        }
        else {
            game.endGameTimesList.Clear();
        }
        if (game.initialForceList == null) {
            game.initialForceList = new List<Vector3>();
        }
        else {
            game.initialForceList.Clear();
        }

        if (numModifiers > 0) {
            int numTargetModifiers = 0;
            for (int i = numModifiers - 1; i >= 0; i--) {  // iterate through all modifiers
                float t = 0f;
                switch (activeTrainingModifierList[i].modifierType) {
                    case TrainingModifier.TrainingModifierType.LinkExplosion:

                        break;

                    case TrainingModifier.TrainingModifierType.MutationBlast:
                        
                        break;

                    case TrainingModifier.TrainingModifierType.BodyMutationBlast:

                        break;

                    case TrainingModifier.TrainingModifierType.PruneBrain:
                        
                        break;

                    case TrainingModifier.TrainingModifierType.TargetCone:
                        numTargetModifiers++;
                        numRounds += activeTrainingModifierList[i].numRounds;

                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        if(t > 1f) {
                            t = 1f;
                        }
                        
                        for (int c = 0; c < activeTrainingModifierList[i].numRounds; c++) {
                            float horAngle = 0f;
                            float verAngle = 0f;
                            float minAngle = Mathf.Lerp(activeTrainingModifierList[i].beginMinAngle, activeTrainingModifierList[i].endMinAngle, t);
                            float maxAngle = Mathf.Lerp(activeTrainingModifierList[i].beginMaxAngle, activeTrainingModifierList[i].endMaxAngle, t);
                            if (activeTrainingModifierList[i].horizontal) {
                                horAngle = UnityEngine.Random.Range(minAngle, maxAngle) * Mathf.PI / 180f;
                                // Flip to negative axis check
                                if (UnityEngine.Random.Range(0f, 1f) < 0.5f) {
                                    horAngle *= -1f;
                                }
                            }
                            if (activeTrainingModifierList[i].vertical) {
                                verAngle = UnityEngine.Random.Range(minAngle, maxAngle) * Mathf.PI / 180f;
                                if (UnityEngine.Random.Range(0f, 1f) < 0.5f) {
                                    verAngle *= -1f;
                                }
                            }
                            
                            float minDist = Mathf.Lerp(activeTrainingModifierList[i].beginMinDistance, activeTrainingModifierList[i].endMinDistance, t);
                            float maxDist = Mathf.Lerp(activeTrainingModifierList[i].beginMaxDistance, activeTrainingModifierList[i].endMaxDistance, t);
                            float dist = UnityEngine.Random.Range(minDist, maxDist);

                            Vector2 hor = new Vector2(Mathf.Sin(horAngle) * dist, Mathf.Cos(horAngle) * dist).normalized;
                            float x = Mathf.Sin(horAngle) * dist * Mathf.Cos(verAngle);
                            float z = Mathf.Cos(horAngle) * dist * Mathf.Cos(verAngle);
                            float y = Mathf.Sin(verAngle) * dist;

                            game.targetPositionList.Add(new Vector3(x, y, z));
                            int randEndTime = Mathf.RoundToInt(UnityEngine.Random.Range(trainer.PlayerList[0].masterTrialsList[0].minEvaluationTimeSteps, trainer.PlayerList[0].masterTrialsList[0].maxEvaluationTimeSteps)); 
                            game.endGameTimesList.Add(randEndTime);
                            gameRoundIndex++;

                            Vector3 forceDir = UnityEngine.Random.onUnitSphere;
                            float forceMag = UnityEngine.Random.Range(game.customSettings.initForceMin[0], game.customSettings.initForceMax[0]);
                            game.initialForceList.Add(new Vector3(forceDir.x * forceMag, forceDir.y * forceMag, forceDir.z * forceMag));
                        }

                        break;

                    case TrainingModifier.TrainingModifierType.TargetForward:
                        numTargetModifiers++;
                        numRounds += activeTrainingModifierList[i].numRounds;

                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        if (t > 1f) {
                            t = 1f;
                        }

                        for (int c = 0; c < activeTrainingModifierList[i].numRounds; c++) {
                            
                            float minDist = Mathf.Lerp(activeTrainingModifierList[i].beginMinDistance, activeTrainingModifierList[i].endMinDistance, t);
                            float maxDist = Mathf.Lerp(activeTrainingModifierList[i].beginMaxDistance, activeTrainingModifierList[i].endMaxDistance, t);
                            float dist = UnityEngine.Random.Range(minDist, maxDist);

                            game.targetPositionList.Add(new Vector3(0f, 0f, dist));
                            int randEndTime = Mathf.RoundToInt(UnityEngine.Random.Range(trainer.PlayerList[0].masterTrialsList[0].minEvaluationTimeSteps, trainer.PlayerList[0].masterTrialsList[0].maxEvaluationTimeSteps));
                            game.endGameTimesList.Add(randEndTime);
                            gameRoundIndex++;

                            Vector3 forceDir = UnityEngine.Random.onUnitSphere;
                            float forceMag = UnityEngine.Random.Range(game.customSettings.initForceMin[0], game.customSettings.initForceMax[0]);
                            game.initialForceList.Add(new Vector3(forceDir.x * forceMag, forceDir.y * forceMag, forceDir.z * forceMag));
                        }

                        break;

                    case TrainingModifier.TrainingModifierType.TargetOmni:
                        numTargetModifiers++;
                        numRounds += activeTrainingModifierList[i].numRounds;

                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        if (t > 1f) {
                            t = 1f;
                        }

                        for (int c = 0; c < activeTrainingModifierList[i].numRounds; c++) {

                            float randX = 0f;
                            float randY = 0f;
                            float randZ = 0f;
                            if(activeTrainingModifierList[i].horizontal) {
                                randX = UnityEngine.Random.Range(-1f, 1f);
                            }
                            if (activeTrainingModifierList[i].vertical) {
                                randY = UnityEngine.Random.Range(-1f, 1f);
                            }
                            if (activeTrainingModifierList[i].forward) {
                                randZ = UnityEngine.Random.Range(-1f, 1f);
                            }                         
                            Vector3 randDir = new Vector3(randX, randY, randZ).normalized;
                            
                            float minDist = Mathf.Lerp(activeTrainingModifierList[i].beginMinDistance, activeTrainingModifierList[i].endMinDistance, t);
                            float maxDist = Mathf.Lerp(activeTrainingModifierList[i].beginMaxDistance, activeTrainingModifierList[i].endMaxDistance, t);
                            float dist = UnityEngine.Random.Range(minDist, maxDist);
                            
                            game.targetPositionList.Add(new Vector3(randDir.x * dist, randDir.y * dist, randDir.z * dist));
                            int randEndTime = Mathf.RoundToInt(UnityEngine.Random.Range(trainer.PlayerList[0].masterTrialsList[0].minEvaluationTimeSteps, trainer.PlayerList[0].masterTrialsList[0].maxEvaluationTimeSteps));
                            game.endGameTimesList.Add(randEndTime);
                            gameRoundIndex++;

                            Vector3 forceDir = UnityEngine.Random.onUnitSphere;
                            float forceMag = UnityEngine.Random.Range(game.customSettings.initForceMin[0], game.customSettings.initForceMax[0]);
                            game.initialForceList.Add(new Vector3(forceDir.x * forceMag, forceDir.y * forceMag, forceDir.z * forceMag));
                        }

                        break;

                    case TrainingModifier.TrainingModifierType.VariableTrialTimes:
                        
                        break;

                    case TrainingModifier.TrainingModifierType.WideSearch:
                        
                        break;

                    default:
                        Debug.Log("Modifier type not found!!! SWITCH DEFAULT CASE");
                        break;
                }
            }
            if(numTargetModifiers == 0) {
                // proceed as default
                minigame.ResetTargetPositions(trainer.PlayerList[0].masterTrialsList[0].numberOfPlays, trainer.PlayerList[0].masterTrialsList[0].minEvaluationTimeSteps, trainer.PlayerList[0].masterTrialsList[0].maxEvaluationTimeSteps);
            }
            else {
                trainer.PlayerList[0].masterTrialsList[0].numberOfPlays = numRounds;
            }            
        }
        else {  // No Modifiers!
            minigame.ResetTargetPositions(trainer.PlayerList[0].masterTrialsList[0].numberOfPlays, trainer.PlayerList[0].masterTrialsList[0].minEvaluationTimeSteps, trainer.PlayerList[0].masterTrialsList[0].maxEvaluationTimeSteps);
        }
    }
        /// <summary>
        /// This builds the <see cref="TermMap"/> instances per column.
        /// </summary>
        private static TermMap[] Train(IHostEnvironment env, IChannel ch, ColInfo[] infos,
                                       ArgumentsBase args, ColumnBase[] column, IDataView trainingData)
        {
            Contracts.AssertValue(env);
            env.AssertValue(ch);
            ch.AssertValue(infos);
            ch.AssertValue(args);
            ch.AssertValue(column);
            ch.AssertValue(trainingData);

            if ((args.Term != null || !string.IsNullOrEmpty(args.Terms)) &&
                (!string.IsNullOrWhiteSpace(args.DataFile) || args.Loader.IsGood() ||
                 !string.IsNullOrWhiteSpace(args.TermsColumn)))
            {
                ch.Warning("Explicit term list specified. Data file arguments will be ignored");
            }

            if (!Enum.IsDefined(typeof(SortOrder), args.Sort))
            {
                throw ch.ExceptUserArg(nameof(args.Sort), "Undefined sorting criteria '{0}' detected", args.Sort);
            }

            TermMap termsFromFile = null;
            var     termMap       = new TermMap[infos.Length];

            int[]         lims         = new int[infos.Length];
            int           trainsNeeded = 0;
            HashSet <int> toTrain      = null;

            for (int iinfo = 0; iinfo < infos.Length; iinfo++)
            {
                // First check whether we have a terms argument, and handle it appropriately.
                var terms      = new DvText(column[iinfo].Terms);
                var termsArray = column[iinfo].Term;
                if (!terms.HasChars && termsArray == null)
                {
                    terms      = new DvText(args.Terms);
                    termsArray = args.Term;
                }

                terms = terms.Trim();
                if (terms.HasChars || (termsArray != null && termsArray.Length > 0))
                {
                    // We have terms! Pass it in.
                    var sortOrder = column[iinfo].Sort ?? args.Sort;
                    if (!Enum.IsDefined(typeof(SortOrder), sortOrder))
                    {
                        throw ch.ExceptUserArg(nameof(args.Sort), "Undefined sorting criteria '{0}' detected for column '{1}'", sortOrder, infos[iinfo].Name);
                    }

                    var bldr = Builder.Create(infos[iinfo].TypeSrc, sortOrder);
                    if (terms.HasChars)
                    {
                        bldr.ParseAddTermArg(ref terms, ch);
                    }
                    else
                    {
                        bldr.ParseAddTermArg(termsArray, ch);
                    }
                    termMap[iinfo] = bldr.Finish();
                }
                else if (!string.IsNullOrWhiteSpace(args.DataFile))
                {
                    // First column using this file.
                    if (termsFromFile == null)
                    {
                        var bldr = Builder.Create(infos[iinfo].TypeSrc, column[iinfo].Sort ?? args.Sort);
                        termsFromFile = CreateFileTermMap(env, ch, args, bldr);
                    }
                    if (!termsFromFile.ItemType.Equals(infos[iinfo].TypeSrc.ItemType))
                    {
                        // We have no current plans to support re-interpretation based on different column
                        // type, not only because it's unclear what realistic customer use-cases for such
                        // a complicated feature would be, and also because it's difficult to see how we
                        // can logically reconcile "reinterpretation" for different types with the resulting
                        // data view having an actual type.
                        throw ch.ExceptUserArg(nameof(args.DataFile), "Data file terms loaded as type '{0}' but mismatches column '{1}' item type '{2}'",
                                               termsFromFile.ItemType, infos[iinfo].Name, infos[iinfo].TypeSrc.ItemType);
                    }
                    termMap[iinfo] = termsFromFile;
                }
                else
                {
                    // Auto train this column. Leave the term map null for now, but set the lim appropriately.
                    lims[iinfo] = column[iinfo].MaxNumTerms ?? args.MaxNumTerms;
                    ch.CheckUserArg(lims[iinfo] > 0, nameof(Column.MaxNumTerms), "Must be positive");
                    Utils.Add(ref toTrain, infos[iinfo].Source);
                    ++trainsNeeded;
                }
            }

            ch.Assert((Utils.Size(toTrain) == 0) == (trainsNeeded == 0));
            ch.Assert(Utils.Size(toTrain) <= trainsNeeded);
            if (trainsNeeded > 0)
            {
                Trainer[] trainer     = new Trainer[trainsNeeded];
                int[]     trainerInfo = new int[trainsNeeded];
                // Open the cursor, then instantiate the trainers.
                int itrainer;
                using (var cursor = trainingData.GetRowCursor(toTrain.Contains))
                    using (var pch = env.StartProgressChannel("Building term dictionary"))
                    {
                        long   rowCur   = 0;
                        double rowCount = trainingData.GetRowCount(true) ?? double.NaN;
                        var    header   = new ProgressHeader(new[] { "Total Terms" }, new[] { "examples" });

                        itrainer = 0;
                        for (int iinfo = 0; iinfo < infos.Length; ++iinfo)
                        {
                            if (termMap[iinfo] != null)
                            {
                                continue;
                            }
                            var bldr = Builder.Create(infos[iinfo].TypeSrc, column[iinfo].Sort ?? args.Sort);
                            trainerInfo[itrainer] = iinfo;
                            trainer[itrainer++]   = Trainer.Create(cursor, infos[iinfo].Source, false, lims[iinfo], bldr);
                        }
                        ch.Assert(itrainer == trainer.Length);
                        pch.SetHeader(header,
                                      e =>
                        {
                            e.SetProgress(0, rowCur, rowCount);
                            // Purely feedback for the user. That the other thread might be
                            // working in the background is not a problem.
                            e.SetMetric(0, trainer.Sum(t => t.Count));
                        });

                        // The [0,tmin) trainers are finished.
                        int tmin = 0;
                        // We might exit early if all trainers reach their maximum.
                        while (tmin < trainer.Length && cursor.MoveNext())
                        {
                            rowCur++;
                            for (int t = tmin; t < trainer.Length; ++t)
                            {
                                if (!trainer[t].ProcessRow())
                                {
                                    Utils.Swap(ref trainerInfo[t], ref trainerInfo[tmin]);
                                    Utils.Swap(ref trainer[t], ref trainer[tmin++]);
                                }
                            }
                        }

                        pch.Checkpoint(trainer.Sum(t => t.Count), rowCur);
                    }
                for (itrainer = 0; itrainer < trainer.Length; ++itrainer)
                {
                    int iinfo = trainerInfo[itrainer];
                    ch.Assert(termMap[iinfo] == null);
                    if (trainer[itrainer].Count == 0)
                    {
                        ch.Warning("Term map for output column '{0}' contains no entries.", infos[iinfo].Name);
                    }
                    termMap[iinfo] = trainer[itrainer].Finish();
                    // Allow the intermediate structures in the trainer and builder to be released as we iterate
                    // over the columns, as the Finish operation can potentially result in the allocation of
                    // additional structures.
                    trainer[itrainer] = null;
                }
                ch.Assert(termMap.All(tm => tm != null));
                ch.Assert(termMap.Zip(infos, (tm, info) => tm.ItemType.Equals(info.TypeSrc.ItemType)).All(x => x));
            }

            return(termMap);
        }
Exemple #46
0
 public bool UpdateTrainer(Trainer trainer)
 {
     return(trainerRepositories.UpdateTrainer(trainer));
 }
        /// <summary>
        /// Utility method to create the file-based <see cref="TermMap"/> if the <see cref="ArgumentsBase.DataFile"/>
        /// argument of <paramref name="args"/> was present.
        /// </summary>
        private static TermMap CreateFileTermMap(IHostEnvironment env, IChannel ch, ArgumentsBase args, Builder bldr)
        {
            Contracts.AssertValue(ch);
            ch.AssertValue(env);
            ch.AssertValue(args);
            ch.Assert(!string.IsNullOrWhiteSpace(args.DataFile));
            ch.AssertValue(bldr);

            string file = args.DataFile;
            // First column using the file.
            string src = args.TermsColumn;
            var    sub = args.Loader;
            // If the user manually specifies a loader, or this is already a pre-processed binary
            // file, then we assume the user knows what they're doing and do not attempt to convert
            // to the desired type ourselves.
            bool autoConvert = false;

            if (!sub.IsGood())
            {
                // Determine the default loader from the extension.
                var  ext         = Path.GetExtension(file);
                bool isBinary    = string.Equals(ext, ".idv", StringComparison.OrdinalIgnoreCase);
                bool isTranspose = string.Equals(ext, ".tdv", StringComparison.OrdinalIgnoreCase);
                if (isBinary || isTranspose)
                {
                    ch.Assert(isBinary != isTranspose);
                    ch.CheckUserArg(!string.IsNullOrWhiteSpace(src), nameof(args.TermsColumn),
                                    "Must be specified");
                    if (isBinary)
                    {
                        sub = new SubComponent <IDataLoader, SignatureDataLoader>("BinaryLoader");
                    }
                    else
                    {
                        ch.Assert(isTranspose);
                        sub = new SubComponent <IDataLoader, SignatureDataLoader>("TransposeLoader");
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(src))
                    {
                        ch.Warning(
                            "{0} should not be specified when default loader is TextLoader. Ignoring {0}={1}",
                            nameof(Arguments.TermsColumn), src);
                    }
                    sub         = new SubComponent <IDataLoader, SignatureDataLoader>("TextLoader", "sep=tab col=Term:TX:0");
                    src         = "Term";
                    autoConvert = true;
                }
            }
            ch.AssertNonEmpty(src);

            int colSrc;
            var loader = sub.CreateInstance(env, new MultiFileSource(file));

            if (!loader.Schema.TryGetColumnIndex(src, out colSrc))
            {
                throw ch.ExceptUserArg(nameof(args.TermsColumn), "Unknown column '{0}'", src);
            }
            var typeSrc = loader.Schema.GetColumnType(colSrc);

            if (!autoConvert && !typeSrc.Equals(bldr.ItemType))
            {
                throw ch.ExceptUserArg(nameof(args.TermsColumn), "Must be of type '{0}' but was '{1}'", bldr.ItemType, typeSrc);
            }

            using (var cursor = loader.GetRowCursor(col => col == colSrc))
                using (var pch = env.StartProgressChannel("Building term dictionary from file"))
                {
                    var    header   = new ProgressHeader(new[] { "Total Terms" }, new[] { "examples" });
                    var    trainer  = Trainer.Create(cursor, colSrc, autoConvert, int.MaxValue, bldr);
                    double rowCount = loader.GetRowCount(true) ?? double.NaN;
                    long   rowCur   = 0;
                    pch.SetHeader(header,
                                  e =>
                    {
                        e.SetProgress(0, rowCur, rowCount);
                        // Purely feedback for the user. That the other thread might be
                        // working in the background is not a problem.
                        e.SetMetric(0, trainer.Count);
                    });
                    while (cursor.MoveNext() && trainer.ProcessRow())
                    {
                        rowCur++;
                    }
                    if (trainer.Count == 0)
                    {
                        ch.Warning("Term map loaded from file resulted in an empty map.");
                    }
                    pch.Checkpoint(trainer.Count, rowCur);
                    return(trainer.Finish());
                }
        }
Exemple #48
0
 void Start()
 {
     trainer = GameObject.Find("Player").GetComponent<Trainer>();
     gameObject.AddComponent ("CameraControl");
 }
 public void Update(Trainer t)
 {
     db.Entry(t).State = EntityState.Modified;
     db.SaveChanges();
 }
Exemple #50
0
        /// <summary>
        /// TrainAndEvaluateWithFlowerData shows how to do transfer learning with a MinibatchSource. MinibatchSource is constructed with
        /// a map file that contains image file paths and labels. Data loading, image preprocessing, and batch randomization are handled
        /// by MinibatchSource.
        /// </summary>
        /// <param name="device">CPU or GPU device to run</param>
        /// <param name="forceReTrain">Force to train the model if true. If false,
        /// it only evaluates the model is it exists. </param>
        public static void TrainAndEvaluateWithFlowerData(DeviceDescriptor device, bool forceReTrain = false)
        {
            string flowerFolder          = Path.Combine(ExampleImageFoler, "Flowers");
            string flowersTrainingMap    = Path.Combine(flowerFolder, "1k_img_map.txt");
            string flowersValidationMap  = Path.Combine(flowerFolder, "val_map.txt");
            int    flowerModelNumClasses = 102;

            string flowerModelFile = Path.Combine(CurrentFolder, "FlowersTransferLearning.model");

            // If the model exists and it is not set to force retrain, validate the model and return.
            if (File.Exists(flowerModelFile) && !forceReTrain)
            {
                ValidateModelWithMinibatchSource(flowerModelFile, flowersValidationMap,
                                                 imageDims, flowerModelNumClasses, device);
                return;
            }

            // prepare training data
            MinibatchSource minibatchSource = CreateMinibatchSource(flowersTrainingMap,
                                                                    imageDims, flowerModelNumClasses);
            var featureStreamInfo = minibatchSource.StreamInfo("image");
            var labelStreamInfo   = minibatchSource.StreamInfo("labels");

            string   predictionNodeName = "prediction";
            Variable imageInput, labelInput;
            Function trainingLoss, predictionError;

            // create a transfer model
            Function transferLearningModel = CreateTransferLearningModel(BaseResnetModelFile, featureNodeName,
                                                                         predictionNodeName, lastHiddenNodeName, flowerModelNumClasses, device,
                                                                         out imageInput, out labelInput, out trainingLoss, out predictionError);

            // prepare for training
            int   numMinibatches           = 100;
            int   minibatchbSize           = 50;
            float learningRatePerMinibatch = 0.2F;
            float momentumPerMinibatch     = 0.9F;
            float l2RegularizationWeight   = 0.05F;

            AdditionalLearningOptions additionalLearningOptions = new AdditionalLearningOptions()
            {
                l2RegularizationWeight = l2RegularizationWeight
            };

            IList <Learner> parameterLearners = new List <Learner>()
            {
                Learner.MomentumSGDLearner(transferLearningModel.Parameters(),
                                           new TrainingParameterScheduleDouble(learningRatePerMinibatch, 0),
                                           new TrainingParameterScheduleDouble(momentumPerMinibatch, 0),
                                           true,
                                           additionalLearningOptions)
            };
            var trainer = Trainer.CreateTrainer(transferLearningModel, trainingLoss, predictionError, parameterLearners);

            // train the model
            int outputFrequencyInMinibatches = 1;

            for (int minibatchCount = 0; minibatchCount < numMinibatches; ++minibatchCount)
            {
                var minibatchData = minibatchSource.GetNextMinibatch((uint)minibatchbSize, device);

                trainer.TrainMinibatch(new Dictionary <Variable, MinibatchData>()
                {
                    { imageInput, minibatchData[featureStreamInfo] },
                    { labelInput, minibatchData[labelStreamInfo] }
                }, device);
                TestHelper.PrintTrainingProgress(trainer, minibatchCount, outputFrequencyInMinibatches);
            }

            // save the model
            transferLearningModel.Save(flowerModelFile);

            // validate the trained model
            ValidateModelWithMinibatchSource(flowerModelFile, flowersValidationMap,
                                             imageDims, flowerModelNumClasses, device);
        }
    public void ApplyTrainingModifierEffects(Trainer trainer) {

        int currentGen = trainer.PlayingCurGeneration;
        if(trainer.loadedTrainingSave != null) {
            currentGen += trainer.loadedTrainingSave.endGeneration;
        }
        //Debug.Log("ApplyTrainingModifierEffects  currentGen: " + currentGen.ToString());
        CrossoverManager crossoverManager = trainer.PlayerList[0].masterCupid;
        int numModifiers = activeTrainingModifierList.Count;
        crossoverManager.mutationBlastModifier = 1f;
        crossoverManager.bodyMutationBlastModifier = 1f;
        if (numModifiers > 0) {
            for (int i = numModifiers - 1; i >= 0; i--) {
                float t = 0f;
                switch (activeTrainingModifierList[i].modifierType) {
                    case TrainingModifier.TrainingModifierType.LinkExplosion:

                        // go through all agents and pump them up -- THIS WILL NEED IMPROVEMENTS!!!!
                        for (int a = 0; a < trainer.PlayerList[0].masterPopulation.masterAgentArray.Length; a++) {
                            GenomeNEAT genome = trainer.PlayerList[0].masterPopulation.masterAgentArray[a].brainGenome;
                            int numNodes = genome.nodeNEATList.Count;
                            int numNewLinks = (int)((float)numNodes * activeTrainingModifierList[i].linksPerNode);
                            for (int n = 0; n < numNewLinks; n++) {
                                genome.AddNewRandomLink(currentGen);
                            }
                            int numLinks = genome.linkNEATList.Count;
                            int numNewNodes = (int)((float)numLinks * activeTrainingModifierList[i].nodesPerLink);
                            for (int b = 0; b < numNewNodes; b++) {
                                genome.AddNewRandomNode(currentGen, crossoverManager.GetNextAddonInnov());
                            }
                        }
                        activeTrainingModifierList.RemoveAt(i);
                        break;

                    case TrainingModifier.TrainingModifierType.MutationBlast:
                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        crossoverManager = trainer.PlayerList[0].masterCupid;
                        if (t > 1f) {
                            if(activeTrainingModifierList[i].liveForever) {
                                t = 1f;
                            }
                            else {
                                // Duration has expired, and the live forever flag if false, so remove this modifier
                                crossoverManager.mutationBlastModifier = 1f;
                                activeTrainingModifierList.RemoveAt(i);
                                break;
                            }
                        }
                        crossoverManager.mutationBlastModifier = Mathf.Lerp(1f, activeTrainingModifierList[i].minMultiplier, t);
                        break;

                    case TrainingModifier.TrainingModifierType.BodyMutationBlast:
                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        crossoverManager = trainer.PlayerList[0].masterCupid;
                        if (t > 1f) {
                            if (activeTrainingModifierList[i].liveForever) {
                                t = 1f;
                            }
                            else {
                                // Duration has expired, and the live forever flag if false, so remove this modifier
                                crossoverManager.bodyMutationBlastModifier = 1f;
                                activeTrainingModifierList.RemoveAt(i);
                                break;
                            }
                        }
                        crossoverManager.bodyMutationBlastModifier = Mathf.Lerp(1f, activeTrainingModifierList[i].minMultiplier, t);
                        break;

                    case TrainingModifier.TrainingModifierType.PruneBrain:
                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        crossoverManager = trainer.PlayerList[0].masterCupid;
                        if (t > 1f) {
                            t = 1f;
                        }
                        t = 1f - t;
                        crossoverManager.largeBrainPenalty = activeTrainingModifierList[i].largeBrainPenalty * t;
                        crossoverManager.mutationRemoveLinkChance = activeTrainingModifierList[i].removeLinkChance * t;
                        crossoverManager.mutationRemoveNodeChance = activeTrainingModifierList[i].removeNodeChance * t;
                        break;

                    case TrainingModifier.TrainingModifierType.TargetCone:

                        break;

                    case TrainingModifier.TrainingModifierType.TargetForward:

                        break;

                    case TrainingModifier.TrainingModifierType.TargetOmni:

                        break;

                    case TrainingModifier.TrainingModifierType.VariableTrialTimes:
                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        Trial trial = trainer.PlayerList[0].masterTrialsList[0];
                        if (t > 1f) {
                            if(activeTrainingModifierList[i].liveForever) {
                                t = 1f;
                            }
                            else {
                                // Remove this modifier
                                activeTrainingModifierList.RemoveAt(i);
                            }
                        }
                        int minSteps = (int)Mathf.Lerp(activeTrainingModifierList[i].beginMinTime, activeTrainingModifierList[i].endMinTime, t);
                        int maxSteps = (int)Mathf.Lerp(activeTrainingModifierList[i].beginMaxTime, activeTrainingModifierList[i].endMaxTime, t);
                        trial.maxEvaluationTimeSteps = maxSteps; // (int)UnityEngine.Random.Range(minSteps, maxSteps);
                        trial.minEvaluationTimeSteps = minSteps;
                        break;

                    case TrainingModifier.TrainingModifierType.WideSearch:
                        t = ((float)currentGen - (float)activeTrainingModifierList[i].startGen) / (float)activeTrainingModifierList[i].duration;
                        crossoverManager = trainer.PlayerList[0].masterCupid;
                        if (t > 1f) {
                            t = 1f;
                        }
                        t = 1f - t;
                        //crossoverManager.largeBrainPenalty = activeTrainingModifierList[i].largeBrainPenalty * t;
                        //crossoverManager.mutationRemoveLinkChance = activeTrainingModifierList[i].removeLinkChance * t;
                        //crossoverManager.mutationRemoveNodeChance = activeTrainingModifierList[i].removeNodeChance * t;
                        break;

                    default:
                        Debug.Log("Modifier type not found!!! SWITCH DEFAULT CASE");
                        break;
                }
            }
        }        
    }
 public void Delete(Trainer t)
 {
     db.Entry(t).State = EntityState.Deleted;
     db.SaveChanges();
 }
Exemple #53
0
 public bool SaveStudent(Trainer trainer)
 {
     return(trainerRepositories.SaveStudent(trainer));
 }
Exemple #54
0
        public static void Run()
        {
            Stopwatch sw = new Stopwatch();

            //MNISTのデータを用意する
            Console.WriteLine("Fashion-MNIST Data Loading...");
            FashionMnistData mnistData = new FashionMnistData();

            //ネットワークの構成を FunctionStack に書き連ねる
            FunctionStack nn = new FunctionStack(
                new Convolution2D(1, 32, 5, pad: 2, name: "l1 Conv2D", activation: new ReLU(name: "l1 ReLU"), gpuEnable: true),
                new MaxPooling2D(2, 2, name: "l1 MaxPooling", gpuEnable: true),
                new Convolution2D(32, 64, 5, pad: 2, name: "l2 Conv2D", activation: new ReLU(name: "l2 ReLU"), gpuEnable: true),
                new MaxPooling2D(2, 2, name: "l2 MaxPooling", gpuEnable: true),
                new Linear(7 * 7 * 64, 1024, name: "l3 Linear", activation: new ReLU(name: "l3 ReLU"), gpuEnable: true),
                new Dropout(name: "l3 DropOut"),
                new Linear(1024, 10, name: "l4 Linear", gpuEnable: true)
                );

            //optimizerを宣言
            nn.SetOptimizer(new Adam());

            Console.WriteLine("Training Start...");

            //三世代学習
            for (int epoch = 1; epoch < 3; epoch++)
            {
                Console.WriteLine("epoch " + epoch);

                //全体での誤差を集計
                Real totalLoss      = 0;
                long totalLossCount = 0;

                //何回バッチを実行するか
                for (int i = 1; i < TRAIN_DATA_COUNT + 1; i++)
                {
                    sw.Restart();

                    Console.WriteLine("\nbatch count " + i + "/" + TRAIN_DATA_COUNT);

                    //訓練データからランダムにデータを取得
                    TestDataSet datasetX = mnistData.Train.GetRandomDataSet(BATCH_DATA_COUNT);

                    //バッチ学習を並列実行する
                    Real sumLoss = Trainer.Train(nn, datasetX, new SoftmaxCrossEntropy());
                    totalLoss += sumLoss;
                    totalLossCount++;

                    //結果出力
                    Console.WriteLine("total loss " + totalLoss / totalLossCount);
                    Console.WriteLine("local loss " + sumLoss);

                    sw.Stop();
                    Console.WriteLine("time" + sw.Elapsed.TotalMilliseconds);

                    //20回バッチを動かしたら精度をテストする
                    if (i % 20 == 0)
                    {
                        Console.WriteLine("\nTesting...");

                        //テストデータからランダムにデータを取得
                        TestDataSet datasetY = mnistData.Eval.GetRandomDataSet(TEACH_DATA_COUNT);

                        //テストを実行
                        Real accuracy = Trainer.Accuracy(nn, datasetY);
                        Console.WriteLine("accuracy " + accuracy);
                    }
                }
            }
        }
Exemple #55
0
 public static bool DoesTrainerHaveElement(Trainer trainer, string element)
 {
     return trainer.TrainerPokemons.Any(a => a.PokemonElement == element);
 }
        public static void HandleServerTrainerList(Packet packet)
        {
            var guidBytes = new byte[8];

            guidBytes[0] = packet.ReadBit();
            uint count = packet.ReadBits("Spells", 19);

            packet.StartBitStream(guidBytes, 2, 6);
            uint titleLen = packet.ReadBits(11);

            packet.StartBitStream(guidBytes, 3, 7, 1, 4, 5);
            packet.ResetBitReader();

            var tempList = new List <TrainerSpell>();

            for (int i = 0; i < count; ++i)
            {
                TrainerSpell trainerSpell = new TrainerSpell
                {
                    ReqSkillLine = packet.ReadUInt32("ReqSkillLine", i),
                    ReqSkillRank = packet.ReadUInt32("ReqSkillRank", i),
                    MoneyCost    = packet.ReadUInt32("MoneyCost", i),
                    ReqLevel     = packet.ReadByte("ReqLevel", i),
                    ReqAbility   = new uint[3]
                };
                for (var j = 0; j < 3; ++j)
                {
                    trainerSpell.ReqAbility[j] = packet.ReadUInt32 <SpellId>("ReqAbility", i);
                }

                trainerSpell.SpellId = packet.ReadUInt32 <SpellId>("SpellID", i);
                packet.ReadByteE <TrainerSpellState>("Usable", i);

                tempList.Add(trainerSpell);
            }

            Trainer trainer = new Trainer();

            packet.ReadXORBytes(guidBytes, 3, 2);
            trainer.Greeting = packet.ReadWoWString("Title", titleLen);
            packet.ReadXORBytes(guidBytes, 7, 6, 4, 1, 0, 5);

            trainer.Type = packet.ReadInt32E <TrainerType>("Type");
            trainer.Id   = packet.ReadUInt32("TrainerID");

            packet.WriteGuid("TrainerGUID", guidBytes);
            Storage.Trainers.Add(trainer, packet.TimeSpan);
            tempList.ForEach(trainerSpell =>
            {
                trainerSpell.TrainerId = trainer.Id;
                Storage.TrainerSpells.Add(trainerSpell, packet.TimeSpan);
            });

            var lastGossipOption = CoreParsers.NpcHandler.LastGossipOption;

            if (lastGossipOption.HasSelection)
            {
                if ((packet.TimeSpan - lastGossipOption.TimeSpan).Duration() <= TimeSpan.FromMilliseconds(2500))
                {
                    Storage.CreatureTrainers.Add(new CreatureTrainer {
                        CreatureId = lastGossipOption.Guid.GetEntry(), MenuID = lastGossipOption.MenuId, OptionIndex = lastGossipOption.OptionIndex, TrainerId = trainer.Id
                    }, packet.TimeSpan);
                }
            }
            else
            {
                Storage.CreatureTrainers.Add(new CreatureTrainer {
                    CreatureId = lastGossipOption.Guid.GetEntry(), MenuID = 0, OptionIndex = 0, TrainerId = trainer.Id
                }, packet.TimeSpan);
            }
        }
Exemple #57
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblError.Text = string.Empty;
            string checkResult = CheckForErrors();
            string userid      = "";

            if (checkResult == "OK")
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore <IdentityUser>();
                var manager   = new UserManager <IdentityUser>(userStore);
                var user      = new IdentityUser()
                {
                    UserName = txtEmailAddress.Text
                };
                IdentityResult result = manager.Create(user, txtPassword.Text);
                userid = user.Id;
                if (result.Succeeded)
                {
                    DbContext = new RolmDBEntities();
                    AspNetUser Muser = new AspNetUser();
                    Muser                = DbContext.AspNetUsers.Where(x => x.UserName == txtEmailAddress.Text && x.Deleted == null).FirstOrDefault();
                    Muser.Email          = txtEmailAddress.Text;
                    Muser.EmailConfirmed = true;

                    Muser.Created        = DateTime.UtcNow;
                    Muser.Deleted        = null;
                    Muser.EmailConfirmed = true;
                    Muser.FullName       = txtFirstName.Text + " " + txtLastName.Text;
                    Muser.PhoneNumber    = "000000000";
                    Muser.UserName       = txtEmailAddress.Text;
                    Muser.GymId          = 0;
                    switch (RadioButtonList1.SelectedItem.Value.Trim())
                    {
                    case "Gym Owner":
                        Muser.LastAccessedSystemTypeId = (int)Enum.Parse(typeof(Dal.EnumTypes.SystemTypes), Dal.EnumTypes.SystemTypes.Gym.ToString());
                        break;

                    case "Personal Trainer":
                        Muser.LastAccessedSystemTypeId = (int)Enum.Parse(typeof(Dal.EnumTypes.SystemTypes), Dal.EnumTypes.SystemTypes.Trainer.ToString());
                        Trainer train = new Trainer();
                        train.EmailAddress = txtEmailAddress.Text;
                        train.Gender       = RadioButtonList2.SelectedItem.Value.Trim();
                        train.FirstName    = txtFirstName.Text;
                        train.LastName     = txtLastName.Text;
                        train.UserId       = userid;
                        train.Created      = DateTime.UtcNow;
                        train.DBImageId    = DbContext.DBImages.Where(x => x.Deleted == null).OrderBy(x => x.Id).FirstOrDefault().Id;
                        train.Nationality  = 1;
                        train.CountryId    = 1;
                        DbContext.Trainers.Add(train);
                        DbContext.SaveChanges();
                        GymTrainer gymTrainer = new GymTrainer();

                        gymTrainer.GymId     = Convert.ToInt64(ddlGyms.SelectedValue);
                        gymTrainer.TrainerId = train.Id;
                        gymTrainer.Created   = DateTime.UtcNow;
                        DbContext.GymTrainers.Add(gymTrainer);
                        DbContext.SaveChanges();
                        break;

                    case "Fitness Fanatic":

                        Muser.LastAccessedSystemTypeId = (int)Enum.Parse(typeof(Dal.EnumTypes.SystemTypes), Dal.EnumTypes.SystemTypes.Customer.ToString());
                        var Customeruser = DbContext.Customers.Where(x => x.EmailAddress == txtEmailAddress.Text).FirstOrDefault();

                        Customer customer = new Customer();
                        customer.EmailAddress = txtEmailAddress.Text;
                        customer.Gender       = RadioButtonList2.SelectedItem.Value.Trim();
                        customer.FirstName    = txtFirstName.Text;
                        customer.LastName     = txtLastName.Text;
                        customer.UserId       = userid;
                        customer.Created      = DateTime.UtcNow;
                        customer.DBImageId    = DbContext.DBImages.Where(x => x.Deleted == null).OrderBy(x => x.Id).FirstOrDefault().Id;
                        customer.Nationality  = 1;
                        customer.CountryId    = 1;
                        DbContext.Customers.Add(customer);
                        DbContext.SaveChanges();

                        GymCustomer gymCustomer = new GymCustomer();
                        gymCustomer.GymId      = Convert.ToInt64(ddlGyms.SelectedValue);
                        gymCustomer.CustomerId = customer.Id;
                        gymCustomer.Created    = DateTime.UtcNow;
                        DbContext.GymCustomers.Add(gymCustomer);
                        DbContext.SaveChanges();

                        break;

                    default:
                        Muser.LastAccessedSystemTypeId = (int)Enum.Parse(typeof(Dal.EnumTypes.SystemTypes), Dal.EnumTypes.SystemTypes.Gym.ToString());
                        break;
                    }


                    DbContext.SaveChanges();

                    switch (RadioButtonList1.SelectedItem.Value.Trim())
                    {
                    case "Gym Owner":
                        //  Response.Redirect("http://gym.rolmfitness.com/Account/Login?id="+ txtEmailAddress.Text.Trim() +"&password="******"http://216.144.248.226:8096/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://localhost:1339/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"Personal Trainer":
                        //   Response.Redirect("http://216.144.248.226:8097/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://216.144.248.226:8097//Schedules/Index?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://trainer.rolmfitness.com/Account/Login?id="+ txtEmailAddress.Text.Trim() +"&password="******"http://localhost:1342/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"Fitness Fanatic":
                        //  Response.Redirect("http://216.144.248.226:8098/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://member.rolmfitness.com/Account/Login?id="+ txtEmailAddress.Text.Trim() +"&password="******"http://localhost:1343/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://216.144.248.226:8096/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://gym.rolmfitness.com/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password="******"http://localhost:1339/Account/Login?id=" + txtEmailAddress.Text.Trim() + "&password=" + txtPassword.Text.Trim());
                        break;
                    }
                }
                else
                {
                    lblError1.Text = result.Errors.FirstOrDefault();
                }
            }
            else
            {
                lblError1.Text = checkResult;
            }
        }
        private List <Trainer> getTrainer(DatabaseStream stream, DatabaseScheme scheme, bool isTemplate)
        {
            List <Trainer> trainers = new List <Trainer>();

            if (scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
            {
                if (stream.SampleRate != scheme.SampleRate)
                {
                    return(trainers);
                }
            }
            string streamName = "";

            string[] streamParts = stream.Name.Split('.');
            if (streamParts.Length <= 1)
            {
                streamName = stream.Name;
            }
            else
            {
                streamName = streamParts[1];
                for (int i = 2; i < streamParts.Length; i++)
                {
                    streamName += "." + streamParts[i];
                }
            }


            string trainerDir = null;

            if (isTemplate)
            {
                trainerDir = Properties.Settings.Default.CMLDirectory + "\\" +
                             Defaults.CML.ModelsFolderName + "\\" +
                             Defaults.CML.ModelsTemplatesFolderName + "\\" +
                             scheme.Type.ToString().ToLower() + "\\" +
                             stream.Type;
            }
            else
            {
                trainerDir = Properties.Settings.Default.CMLDirectory + "\\" +
                             Defaults.CML.ModelsFolderName + "\\" +
                             Defaults.CML.ModelsTrainerFolderName + "\\" +
                             scheme.Type.ToString().ToLower() + "\\" +
                             scheme.Name + "\\" +
                             stream.Type + "{" +
                             streamName + "}\\";
            }

            if (Directory.Exists(trainerDir))
            {
                string[] searchDirs = Directory.GetDirectories(trainerDir);
                foreach (string searchDir in searchDirs)
                {
                    string[] trainerFiles = Directory.GetFiles(searchDir, "*." + Defaults.CML.TrainerFileExtension);
                    foreach (string trainerFile in trainerFiles)
                    {
                        Trainer trainer = new Trainer()
                        {
                            Path = trainerFile
                        };
                        if (parseTrainerFile(ref trainer, isTemplate))
                        {
                            trainers.Add(trainer);
                        }
                    }
                }
            }

            return(trainers);
        }
        public static void HandleServerTrainerList(Packet packet)
        {
            var guid = new byte[8];

            guid[4] = packet.ReadBit();
            guid[5] = packet.ReadBit();
            int  count    = (int)packet.ReadBits("Spells", 19);
            uint titleLen = packet.ReadBits(11);

            guid[6] = packet.ReadBit();
            guid[2] = packet.ReadBit();
            guid[7] = packet.ReadBit();
            guid[1] = packet.ReadBit();
            guid[3] = packet.ReadBit();
            guid[0] = packet.ReadBit();

            packet.ReadXORByte(guid, 4);

            var tempList = new List <TrainerSpell>();

            for (int i = 0; i < count; ++i)
            {
                TrainerSpell trainerSpell = new TrainerSpell
                {
                    ReqLevel   = packet.ReadByte("ReqLevel", i),
                    MoneyCost  = packet.ReadUInt32("MoneyCost", i),
                    SpellId    = packet.ReadUInt32 <SpellId>("SpellID", i),
                    ReqAbility = new uint[3]
                };

                for (int j = 0; j < 3; ++j)
                {
                    trainerSpell.ReqAbility[j] = packet.ReadUInt32("ReqAbility", i, j);
                }

                trainerSpell.ReqSkillLine = packet.ReadUInt32("ReqSkillLine", i);
                trainerSpell.ReqSkillRank = packet.ReadUInt32("ReqSkillRank", i);
                packet.ReadByteE <TrainerSpellState>("Usable", i);

                tempList.Add(trainerSpell);
            }

            Trainer trainer = new Trainer();

            trainer.Greeting = packet.ReadWoWString("Greeting", titleLen);
            packet.ReadXORByte(guid, 6);
            packet.ReadXORByte(guid, 7);
            packet.ReadXORByte(guid, 1);
            packet.ReadXORByte(guid, 3);
            trainer.Id = (uint)packet.ReadInt32("TrainerID");
            packet.ReadXORByte(guid, 5);
            packet.ReadXORByte(guid, 0);
            packet.ReadXORByte(guid, 2);
            trainer.Type = packet.ReadInt32E <TrainerType>("TrainerType");

            packet.WriteGuid("TrainerGUID", guid);
            Storage.Trainers.Add(trainer, packet.TimeSpan);
            tempList.ForEach(trainerSpell =>
            {
                trainerSpell.TrainerId = trainer.Id;
                Storage.TrainerSpells.Add(trainerSpell, packet.TimeSpan);
            });
            CoreParsers.NpcHandler.AddToCreatureTrainers(trainer.Id, packet.TimeSpan);
        }
 public void Insert(Trainer t)
 {
     db.Entry(t).State = EntityState.Added;
     db.SaveChanges();
 }