Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            List <User>    users       = ListOfUsers();
            List <Subject> allSubjects = ListOfSubjects();
            List <Student> students    = users.Where(x => x.Role == Role.Student).Cast <Student>().ToList();

            students[0].Grades = new Dictionary <Subject, int>()
            {
                { allSubjects[0], 3 }, { allSubjects[2], 4 }, { allSubjects[4], 5 }, { allSubjects[6], 5 }
            };
            students[1].Grades = new Dictionary <Subject, int>()
            {
                { allSubjects[2], 4 }, { allSubjects[3], 4 }, { allSubjects[5], 4 }, { allSubjects[7], 5 }
            };
            students[2].Grades = new Dictionary <Subject, int>()
            {
                { allSubjects[1], 5 }, { allSubjects[2], 5 }, { allSubjects[3], 5 }, { allSubjects[4], 5 }
            };
            students[3].Grades = new Dictionary <Subject, int>()
            {
                { allSubjects[0], 3 }, { allSubjects[4], 5 }, { allSubjects[5], 5 }, { allSubjects[6], 3 }
            };
            students[4].Grades = new Dictionary <Subject, int>()
            {
                { allSubjects[3], 4 }, { allSubjects[5], 4 }, { allSubjects[6], 5 }, { allSubjects[7], 5 }
            };

            students[0].CurrentSubject = allSubjects[1];
            students[1].CurrentSubject = allSubjects[6];
            students[2].CurrentSubject = allSubjects[5];
            students[3].CurrentSubject = allSubjects[2];
            students[4].CurrentSubject = allSubjects[2];

            while (true)
            {
                Console.WriteLine("1. Please login or 2.Exit program");

                bool tryInput = int.TryParse(Console.ReadLine(), out int input);

                if (input == 2)
                {
                    break;
                }
                else if (input == 1)
                {
                    Console.Write("Username: "******"Password: "******"there is no user like this");
                        Console.ReadLine();
                    }
                    else if (user.Password != password)
                    {
                        Console.WriteLine("Wrong password");
                        Console.ReadLine();
                    }
                    else
                    {
                        Console.Clear();
                        Console.WriteLine($"Hello {user.Username}");

                        #region RoleAdmin
                        if (user.Role == Role.Admin)
                        {
                            while (true)
                            {
                                Console.WriteLine("Choose 1. Add user  2. Remove user 3.Logout");

                                bool tryInputAdmin = int.TryParse(Console.ReadLine(), out int adminInput);

                                if (adminInput == 1)
                                {
                                    Console.WriteLine("Which type of user you want to add: 1.Admin 2.Trainer 3.Student");

                                    bool tryTypeOfUser = int.TryParse(Console.ReadLine(), out int typeOfUser);

                                    if (tryTypeOfUser && typeOfUser <= 3)
                                    {
                                        Console.Write("Enter new username: "******"Enter new password: "******"Already exist this user please try again");
                                            typeOfUser = 0;
                                        }
                                        else if (typeOfUser == 1)
                                        {
                                            Admin newUser = new Admin(newUsername, newPassword);
                                            users.Add(newUser);
                                        }
                                        else if (typeOfUser == 2)
                                        {
                                            Trainer newUser = new Trainer(newUsername, newPassword);
                                            users.Add(newUser);
                                        }
                                        else if (typeOfUser == 3)
                                        {
                                            Student newUser = new Student(newUsername, newPassword);
                                            var     random  = new Random();
                                            newUser.Grades = new Dictionary <Subject, int>()
                                            {
                                                { allSubjects[random.Next(0, allSubjects.Count - 1)], random.Next(1, 6) }
                                            };
                                            users.Add(newUser);
                                            students.Add(newUser);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("wrong input");
                                    }
                                }
                                else if (adminInput == 2)
                                {
                                    Console.WriteLine();
                                    foreach (var item in users)
                                    {
                                        Console.WriteLine(item.Username);
                                    }
                                    Console.Write("Enter username you want to remove: ");
                                    string userWantToRemove = Console.ReadLine();

                                    if (userWantToRemove == user.Username)
                                    {
                                        Console.WriteLine("Admins cant remove it self");
                                    }
                                    else if (CheckUser(users, userWantToRemove))
                                    {
                                        User userRemove = users.Where(x => x.Username == userWantToRemove).FirstOrDefault();
                                        if (userRemove.Role == Role.Student)
                                        {
                                            Student studentRemove = (Student)userRemove;
                                            students.Remove(studentRemove);
                                        }
                                        users.Remove(userRemove);
                                    }
                                    else
                                    {
                                        Console.WriteLine($"Doesn't exist user like {userWantToRemove}");
                                    }
                                }
                                else if (adminInput == 3)
                                {
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("wrong input");
                                }

                                Console.WriteLine("Press enter");
                                Console.ReadLine();
                                Console.Clear();
                            }
                        }
                        #endregion

                        #region RoleTrainer
                        if (user.Role == Role.Trainer)
                        {
                            while (true)
                            {
                                Console.WriteLine();
                                Console.WriteLine("1.Show all students  2.Show all subjects 3.Logout");

                                bool tryInputTrainer = int.TryParse(Console.ReadLine(), out int trainerInput);

                                if (trainerInput == 1)
                                {
                                    foreach (var student in students)
                                    {
                                        Console.WriteLine(student.Username);
                                    }
                                    Console.WriteLine();
                                    Console.WriteLine("Enter student to show its subjects and grades");
                                    Console.Write("Student: ");
                                    string studentInput = Console.ReadLine();

                                    if (CheckStudent(students, studentInput))
                                    {
                                        Student student = students.Where(x => x.Username == studentInput).FirstOrDefault();
                                        foreach (var studentSubject in student.Grades)
                                        {
                                            Console.WriteLine($"{studentSubject.Key.Name} / Grade: {studentSubject.Value}");
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine($"There is no student like {studentInput}");
                                    }
                                }
                                else if (trainerInput == 2)
                                {
                                    foreach (var subject in allSubjects)
                                    {
                                        subject.StudentsListen = students.Where(x => x.CurrentSubject.Name == subject.Name).ToList();
                                        Console.WriteLine($"{subject.Name} / listening : {subject.StudentsListen.Count}");
                                    }
                                }
                                else if (trainerInput == 3)
                                {
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("wrong input");
                                }


                                Console.WriteLine("Press enter");
                                Console.ReadLine();
                                Console.Clear();
                            }
                        }
                        #endregion

                        #region RoleStudent
                        if (user.Role == Role.Student)
                        {
                            while (true)
                            {
                                Console.WriteLine("Choose: 1.Show your subjects and grades  2.Logout");

                                bool tryInputTrainer = int.TryParse(Console.ReadLine(), out int studentInput);

                                Student student = students.Where(x => x.Username == user.Username).FirstOrDefault();

                                if (studentInput == 1)
                                {
                                    foreach (var item in student.Grades)
                                    {
                                        Console.WriteLine($"{item.Key.Name} / Grade: {item.Value}");
                                    }
                                }
                                else if (studentInput == 2)
                                {
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("wrong input");
                                }

                                Console.WriteLine("Press enter");
                                Console.ReadLine();
                                Console.Clear();
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    Console.WriteLine("Wrong input");
                    Console.ReadLine();
                }
                Console.Clear();
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            #region Conditional

            /*
             * for (int i = 0; i < args.Length; i++)
             * {
             *  if(args[i] == "Friday")
             *  {
             *      if (3 < 5)
             *      {
             *          Console.WriteLine("5 is less than");
             *      }
             *      Console.WriteLine("we will work until 12am");
             *  }
             *  else if(args[i] == "Saturday")
             *  {
             *      Console.WriteLine("Sleep all day");
             *  }
             *  else
             *  {
             *      Console.WriteLine("No work");
             *  }
             *  switch (args[i])
             *  {
             *      case "Friday":
             *          Console.WriteLine("We will work until 12am");
             *          break;
             *      case "Saturday":
             *          Console.WriteLine("Sleep all day");
             *          break;
             *      default:
             *          Console.WriteLine("No Work");
             *          break;
             *  }
             *  int x = 0;
             *  while (args[i] != "Friday" && x == 0)
             *  {
             *
             *      Console.WriteLine("Today is not a friday");
             *      x++;
             *  }
             *  //do
             *  //{
             *  //    Console.WriteLine("Do first");
             *  //}
             *  //while (args[i] != "Friday");
             *  Console.WriteLine("arg:" + i + ",value:" + args[i]);
             * }
             */
            #endregion

            #region Variable & Datatypes
            Console.WriteLine("Hello World! - Today is friday");

            string dayoftheweek = "Friday";
            Console.WriteLine("Today is " + dayoftheweek);

            int dayofmonth = 31;
            Console.WriteLine("Day of the Month:" + dayofmonth);

            double amount = 10.5;
            Console.WriteLine("Amount:" + amount);

            bool valid;
            valid = true;
            Console.WriteLine("Is is Valid:" + valid);

            Address = "Test";
            Console.WriteLine("My address:" + Address);

            object sessions   = "Dot Net Session";
            string newsession = (string)sessions;
            int    a          = 5;
            int    b          = 4;
            int    sum        = Calculation.CalculateSum(a, b);
            Console.WriteLine("a+b=" + sum);
            #endregion

            #region Collection
            LearnCollection learnCollection = new LearnCollection("Python");
            learnCollection.LearnStringList();

            //learnCollection.Langauge = "Python";

            learnCollection.LearnDoubleArray();
            learnCollection.LearnStringArray();
            learnCollection.LearnStringList();


            foreach (string language in learnCollection.Langauages)
            {
                Console.WriteLine(language);
            }
            #endregion


            #region Extension

            Trainer trainer = new Trainer("Mithun");

            trainer.ShowDepartment();

            string mfn = trainer.IsPersonMaleOfFemale();

            Student student = new Student();
            student.IsPersonMaleOfFemale();

            SWeekOfDay sWeek = new SWeekOfDay();
            sWeek.Days   = "Monday";
            sWeek.DValue = 1;

            int x = 5;

            bool result = x.IsGreaterThan(6);

            #endregion

            #region System IO
            //SystemIO systemIO = new SystemIO();
            //systemIO.WriteToFile();
            //systemIO.WriteMultipleLineToFile(learnCollection.Langauages);
            //systemIO.ReadFileFromDirectory();
            //var path = systemIO.WriteToFile();
            //systemIO.ReadFile(path);
            #endregion

            #region Serialization & De

            SerializeDeserialize serializeDeserialize = new SerializeDeserialize();
            string json = serializeDeserialize.Serialization(learnCollection.Langauages);

            List <string> languages = serializeDeserialize.DeSerialization <List <string> >(json);


            List <Person> people = new List <Person>();
            people.Add(new Person()
            {
                FirstName = "Mithun", PhoneNumber = "1234"
            });
            people.Add(new Person()
            {
                FirstName = "Adil", PhoneNumber = "2345"
            });
            people.Add(new Person()
            {
                FirstName = "Minhaz", PhoneNumber = "3456"
            });

            string pjson = serializeDeserialize.Serialization(people);

            List <Person> dpeople = serializeDeserialize.DeSerialization <List <Person> >(pjson);

            #endregion

            #region Delegates
            DelegatesEx delegatesEx = new DelegatesEx();
            // Delegate instantiation
            operation obj = new operation(delegatesEx.Addition);
            int       i   = obj(5, 6);
            Console.WriteLine(i);
            #endregion

            #region Refelction

            System.Type type = learnCollection.GetType();
            System.Console.WriteLine(type);

            #endregion

            #region Tuples

            TupleEx             tuple = new TupleEx();
            Tuple <string, int> t     = tuple.GetTuple();
            Console.WriteLine("Name:" + t.Item1);
            Console.WriteLine("Id:" + t.Item2);

            #endregion

            Console.ReadLine();
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            List <User> users = UserListGenerator.UsersList();

            Roles  userPosition   = Roles.Student;
            bool   loginIsOk      = false;
            string loggedUsername = "";
            string usersName      = "";


            try
            {
                do
                {
                    Menus.MainMenu();
                    string usersChoice = Console.ReadLine();
                    Console.Clear();

                    //Selecting position.
                    Errors.EmptyField(usersChoice);
                    if (usersChoice != "")
                    {
                        userPosition = LoginService.usersPostition(usersChoice);
                    }

                    string userUsername = "", userPassword = "";
                    Menus.UsernamePasswordInput(ref userUsername, ref userPassword);
                    Errors.EmptyFields2(userUsername, userPassword);

                    if (userUsername != "" && userPassword != "")
                    {
                        foreach (User logged in users)
                        {
                            LoginService.CheckLogIn(logged, userUsername, userPassword, userPosition, ref loginIsOk, ref usersName, ref loggedUsername);
                        }

                        if (loginIsOk == false)
                        {
                            Console.WriteLine("Either your username, or your password was wrong.");
                            Console.WriteLine("Try again...");
                            Console.WriteLine();
                        }

                        if (loginIsOk)
                        {
                            Console.WriteLine($"Welcome {usersName}");

                            do
                            {
                                //Shows the sub-menu according to its position.
                                if (userPosition == Roles.Admin)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("List of all users:");
                                    Console.WriteLine();
                                    User.PrintAllUsers(users);
                                    Menus.AdminsSubMenu();
                                    string adminsChoice = Console.ReadLine();
                                    Console.Clear();

                                    //Add new user
                                    if (adminsChoice == "1")
                                    {
                                        string enteredName = "", enteredLastName = "", enteredUserName = "", enteredPassword = "";
                                        Menus.NewUserInfo(ref enteredName, ref enteredLastName, ref enteredUserName, ref enteredPassword);
                                        Errors.EmptyFields3(enteredName, enteredLastName, enteredUserName, enteredPassword);
                                        Menus.PositionSelection();
                                        string enteredPosition = Console.ReadLine();
                                        Errors.WrongPosition(enteredPosition);

                                        if (enteredPosition == "1")
                                        {
                                            Admin newAdmin = new Admin(enteredName, enteredLastName, enteredUserName, enteredPassword);
                                            LoginService.AddNewUser(users, newAdmin);
                                        }

                                        if (enteredPosition == "2")
                                        {
                                            Trainer newTrainer = new Trainer(enteredName, enteredLastName, enteredUserName, enteredPassword);
                                            LoginService.AddNewUser(users, newTrainer);
                                        }

                                        if (enteredPosition == "3")
                                        {
                                            Console.WriteLine("Enter student's subject:");
                                            string enteredSubject = Console.ReadLine();
                                            Errors.EmptyField(enteredSubject);
                                            Errors.WrongSubject(enteredSubject);
                                            Console.WriteLine("Enter student's grade:");
                                            int enteredGrade = int.Parse(Console.ReadLine());
                                            Errors.WrongNumber(enteredGrade);
                                            Student newStudent = new Student(enteredName, enteredLastName, enteredUserName, enteredPassword, enteredSubject, enteredGrade);
                                            LoginService.AddNewUser(users, newStudent);
                                        }
                                    }

                                    //Remove user
                                    if (adminsChoice == "2")
                                    {
                                        Console.WriteLine("Enter user's username that you want to remove:");
                                        string enteredUser = Console.ReadLine();
                                        Console.Clear();
                                        Errors.EmptyField(enteredUser);

                                        if (enteredUser != loggedUsername)
                                        {
                                            var found = LoginService.FindByUsername(users, enteredUser);

                                            if (found == null)
                                            {
                                                Console.WriteLine("User with that username doesn't exist on the list.");
                                            }
                                            else
                                            {
                                                users.Remove(found);
                                                Console.WriteLine($"You've removed user \"{enteredUser}\"");
                                            }
                                        }
                                        else if (enteredUser == loggedUsername)
                                        {
                                            Console.Clear();
                                            Console.WriteLine("You can't remove yourself.");
                                        }
                                    }

                                    if (adminsChoice == "3")
                                    {
                                        LoginService.ResetLogin(ref userUsername, ref userPassword, ref userPosition, ref loginIsOk);
                                        break;
                                    }
                                }

                                //Trainer's menu
                                if (userPosition == Roles.Trainer)
                                {
                                    Menus.TrainerSubMenu();
                                    string teachersChoice = Console.ReadLine();
                                    Console.Clear();

                                    if (teachersChoice == "1")
                                    {
                                        do
                                        {
                                            Console.WriteLine("Student's list:");
                                            Console.WriteLine();
                                            LoginService.ListStudents(LoginService.FilterUsersByDataType(users));
                                            Console.WriteLine();
                                            Console.WriteLine("Press \"E\" if you want to exit.");
                                            teachersChoice = Console.ReadLine();
                                            Errors.WrongExit(teachersChoice);

                                            if (teachersChoice == "e")
                                            {
                                                Console.Clear();
                                                break;
                                            }
                                        } while (true);
                                    }
                                    else if (teachersChoice == "2")
                                    {
                                        do
                                        {
                                            Console.WriteLine("Enter student's name: ");
                                            Console.Write("Search: ");
                                            string teachersInput = Console.ReadLine();
                                            string result        = LoginService.ShowMatch(LoginService.FilterUsersByRole(users, Roles.Student), teachersInput);
                                            Errors.EmptyField(teachersInput);

                                            Console.Clear();
                                            if (result != "")
                                            {
                                                Console.WriteLine(result);
                                            }

                                            if (result == "")
                                            {
                                                Console.WriteLine("Sorry no student by that name.");
                                            }


                                            Console.WriteLine();
                                            Console.WriteLine("Press \"E\" if you want to exit.");
                                            teachersChoice = Console.ReadLine().ToLower();
                                            Errors.WrongExit(teachersChoice);

                                            if (teachersChoice == "e")
                                            {
                                                Console.Clear();
                                                break;
                                            }
                                        } while (true);
                                    }
                                    else if (teachersChoice == "3")
                                    {
                                        do
                                        {
                                            Menus.SelectSubject();
                                            teachersChoice = Console.ReadLine();
                                            Console.Clear();
                                            Errors.WrongSubject3(teachersChoice);

                                            if (int.Parse(teachersChoice) == 1)
                                            {
                                                LoginService.ListStudents(LoginService.FilterStudentsBySubject(users, "C#"));
                                            }

                                            if (int.Parse(teachersChoice) == 2)
                                            {
                                                LoginService.ListStudents(LoginService.FilterStudentsBySubject(users, "JS"));
                                            }

                                            Console.WriteLine();
                                            Console.WriteLine("Press \"E\" if you want to exit.");
                                            teachersChoice = Console.ReadLine().ToLower();
                                            Errors.WrongExit(teachersChoice);

                                            if (teachersChoice == "e")
                                            {
                                                Console.Clear();
                                                break;
                                            }
                                        } while (true);
                                    }
                                    else if (teachersChoice == "4")
                                    {
                                        LoginService.ResetLogin(ref userUsername, ref userPassword, ref userPosition, ref loginIsOk);
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine("You musth choose between 1 and 4.");
                                        Console.WriteLine();
                                    }
                                }

                                if (userPosition == Roles.Student)
                                {
                                    Menus.StudentsMenu();
                                    string studentsChoice = Console.ReadLine();
                                    Console.Clear();
                                    Errors.WrongSubject2(studentsChoice);

                                    if (studentsChoice == "1")
                                    {
                                        do
                                        {
                                            Menus.SubjectSelection();
                                            studentsChoice = Console.ReadLine();

                                            if (studentsChoice == "1")
                                            {
                                                LoginService.SwitchingStudentsSubject(LoginService.FilterUsersByRole(users, Roles.Student), usersName, "C#");
                                            }
                                            else if (studentsChoice == "2")
                                            {
                                                LoginService.SwitchingStudentsSubject(LoginService.FilterUsersByRole(users, Roles.Student), usersName, "JS");
                                            }
                                            else if (studentsChoice.ToLower() == "g")
                                            {
                                                Console.Clear();
                                                Console.WriteLine("Your grade from your current subject.");
                                                Console.WriteLine(LoginService.ShowMatch(LoginService.FilterUsersByRole(users, Roles.Student), usersName));
                                                Console.WriteLine();
                                            }
                                            else if (studentsChoice == "e")
                                            {
                                                Console.Clear();
                                                break;
                                            }
                                            else
                                            {
                                                throw new Exception("You must choose \"1\", \"2\", \"g\" or \"e\".");
                                            }
                                        } while (true);
                                    }

                                    if (studentsChoice == "2")
                                    {
                                        LoginService.ResetLogin(ref userUsername, ref userPassword, ref userPosition, ref loginIsOk);
                                        break;
                                    }
                                }
                            } while (true);
                        }
                    }
                } while (true);
            }
            catch (FormatException)
            {
                Console.WriteLine("You did not enter a correct format.");
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("There is no user with that name.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }
Ejemplo n.º 4
0
        public void Run()
        {
            var device = DeviceDescriptor.UseDefaultDevice();

            // 1. Generate Data
            int sampleSize        = 32;
            int nbDimensionsInput = 2; // 2 dimensions (age&tumorsize)
            int nbLabels          = 2; // l'output est un vecteur de probabilités qui doit sommer à 1. Si on ne met qu'une seule dimension de sortie, l'output sera toujours de 1.
            // on met donc deux dimension, une dimension 'vrai' et une dimension 'faux'. L'output sera du genre 0.25 vrai et 0.75 faux => total des poids = 1;
            // premier label = faux, second = vrai

            IEnumerable <DataPoint> data = GenerateData(sampleSize);

            //foreach (var pt in data)
            //    Debug.WriteLine($"{pt.Age};{pt.TumorSize};{(pt.HasCancer ? 1 : 0)}");

            Variable inputVariables = Variable.InputVariable(NDShape.CreateNDShape(new[] { nbDimensionsInput }), DataType.Double, "input");
            Variable expectedOutput = Variable.InputVariable(new int[] { nbLabels }, DataType.Double, "output");

            Parameter bias    = new Parameter(NDShape.CreateNDShape(new[] { nbLabels }), DataType.Double, 0);                    // une abscisse pour chaque dimension
            Parameter weights = new Parameter(NDShape.CreateNDShape(new[] { nbDimensionsInput, nbLabels }), DataType.Double, 0); // les coefficients à trouver
            // 2 variable d'input, 2 estimations en sortie (proba vrai et proba faux)

            Function predictionFunction = CNTKLib.Plus(CNTKLib.Times(weights, inputVariables), bias);

            Function lossFunction      = CNTKLib.CrossEntropyWithSoftmax(predictionFunction, expectedOutput);
            Function evalErrorFunction = CNTKLib.ClassificationError(predictionFunction, expectedOutput);
            //Function logisticClassifier = CNTKLib.Sigmoid(evaluationFunction, "LogisticClassifier");
            uint minibatchSize = 25;
            //double learningRate = 0.5;
            //TrainingParameterScheduleDouble learningRatePerSample = new TrainingParameterScheduleDouble(learningRate, minibatchSize);

            TrainingParameterScheduleDouble learningRatePerSample = new TrainingParameterScheduleDouble(0.3, (uint)(data.Count() / 1.0));
            TrainingParameterScheduleDouble momentumSchedule      = new TrainingParameterScheduleDouble(0.9126265014311797, minibatchSize);

            var parameters = new ParameterVector();

            foreach (var p in predictionFunction.Parameters())
            {
                parameters.Add(p);
            }

            List <Learner> parameterLearners = new List <Learner>()
            {
                CNTKLib.FSAdaGradLearner(parameters, learningRatePerSample, momentumSchedule, true)
            };

            Trainer trainer = Trainer.CreateTrainer(predictionFunction, lossFunction, evalErrorFunction, parameterLearners);

            double nbSamplesToUseForTraining = 20000;
            int    numMinibatchesToTrain     = (int)(nbSamplesToUseForTraining / (int)minibatchSize);

            // train the model
            for (int minibatchCount = 0; minibatchCount < numMinibatchesToTrain; minibatchCount++)
            {
                IEnumerable <DataPoint> trainingData = GenerateData((int)minibatchSize);

                List <double> minibatchInput  = new List <double>();
                List <double> minibatchOutput = new List <double>();
                foreach (DataPoint row in trainingData)
                {
                    minibatchInput.Add(row.Age);
                    minibatchInput.Add(row.TumorSize);
                    minibatchOutput.Add(row.HasCancer ? 0d : 1d);
                    minibatchOutput.Add(row.HasCancer ? 1d : 0d);
                }


                Value inputData  = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbDimensionsInput }), minibatchInput, device);
                Value outputData = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbLabels }), minibatchOutput, device);

                trainer.TrainMinibatch(new Dictionary <Variable, Value>()
                {
                    { inputVariables, inputData }, { expectedOutput, outputData }
                }, device);

                PrintTrainingProgress(trainer, minibatchCount);
            }

            // test
            {
                int testSize = 100;
                IEnumerable <DataPoint> trainingData = GenerateData(testSize);

                List <double> minibatchInput  = new List <double>();
                List <double> minibatchOutput = new List <double>();
                foreach (DataPoint row in trainingData)
                {
                    minibatchInput.Add(row.Age);
                    minibatchInput.Add(row.TumorSize);
                    minibatchOutput.Add(row.HasCancer ? 0d : 1d);
                    minibatchOutput.Add(row.HasCancer ? 1d : 0d);
                }


                Value inputData  = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbDimensionsInput }), minibatchInput, device);
                Value outputData = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbLabels }), minibatchOutput, device);

                IList <IList <double> > expectedOneHot = outputData.GetDenseData <double>(predictionFunction.Output);
                IList <int>             expectedLabels = expectedOneHot.Select(l => l.IndexOf(1.0d)).ToList();

                var outputDataMap = new Dictionary <Variable, Value>()
                {
                    { predictionFunction.Output, null }
                };
                predictionFunction.Evaluate(
                    new Dictionary <Variable, Value>()
                {
                    { inputVariables, inputData }
                },
                    outputDataMap,
                    device);

                Value outputValue = outputDataMap[predictionFunction.Output];

                IList <IList <double> > actualLabelSoftMax = outputValue.GetDenseData <double>(predictionFunction.Output);
                var actualLabels = actualLabelSoftMax.Select((IList <double> l) => l.IndexOf(l.Max())).ToList();
                int misMatches   = actualLabels.Zip(expectedLabels, (a, b) => a.Equals(b) ? 0 : 1).Sum();

                Debug.WriteLine($"Validating Model: Total Samples = {testSize}, Misclassify Count = {misMatches}");
            }
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            List <Subject> Subjects = new List <Subject>
            {
                new Subject("C#"),
                new Subject("C#Advanced"),
                new Subject("JavaScript"),
                new Subject("HTML"),
                new Subject("JavaScriptAdvanced")
            };

            var subjectGrades = new Dictionary <Subject, int>()
            {
                [Subjects[0]] = 3,
                [Subjects[2]] = 5,
                [Subjects[3]] = 4,
                [Subjects[4]] = 5,
            };
            var subjectGrades1 = new Dictionary <Subject, int>()
            {
                [Subjects[4]] = 1,
                [Subjects[2]] = 2,
            };
            var subjectGrades2 = new Dictionary <Subject, int>()
            {
                [Subjects[4]] = 5,
                [Subjects[2]] = 2,
                [Subjects[0]] = 4,
                [Subjects[1]] = 3,
            };

            List <Person> users = new List <Person>
            {
                new Student("Goran", "Kuzmanoski", "goki_pp", "goki", Subjects[1], subjectGrades),
                new Student("Jovan", "Jovannoski", "jovan", "joco", Subjects[0], subjectGrades1),
                new Student("Vladimir", "Poposki", "vlado", "vlade", Subjects[3], subjectGrades2),
                new Trainer("Trajan", "Stevkoski", "Trajan", "12345"),
                new Admin("Wekoslav", "Stefanoski", "weko", "1x29")
            };

            while (true)
            {
                #region Login
                Person User;
                while (true)
                {
                    Console.WriteLine("Enter username");
                    string inputUsername = Console.ReadLine();
                    User = users.Where(x => x.Username == inputUsername).FirstOrDefault();
                    if (User == null)
                    {
                        Console.WriteLine("Try again");
                        continue;
                    }
                    Console.WriteLine("Enter Password");
                    string inputPassword = Console.ReadLine();
                    if (User.ValidPassword(inputPassword))
                    {
                        Console.WriteLine("Correct password");
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                #endregion
                #region Admin
                while (true)
                {
                    if (User.Role == Role.Admin)
                    {
                        Console.WriteLine("1.Add; 2.Remove");
                        string adminOption = Console.ReadLine();

                        while (adminOption == "1")
                        {
                            Console.WriteLine("1.Add trainer; 2.Add admin; 3.Add student");
                            string addOption = Console.ReadLine();
                            while (addOption == "1")
                            {
                                //adding trainer
                                Console.WriteLine("Enter trainer first name:");
                                string trainerName = Console.ReadLine();
                                Console.WriteLine("Enter trainer last name:");
                                string trainerLastName = Console.ReadLine();
                                Console.WriteLine("Enter trainer username:"******"Enter trainer password:"******"You added new trainer {trainerName} , {trainerLastName}");
                                Console.WriteLine($"-----------------------");
                                Console.WriteLine($"Do you want to add another trainer Y/N");
                                string addTrainerCheck = Console.ReadLine().ToLower();
                                if (addTrainerCheck == "n")
                                {
                                    Console.WriteLine("Thank you for adding new trainer");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            while (addOption == "2")
                            {
                                //adding admin
                                Console.WriteLine("Enter admin first name:");
                                string adminName = Console.ReadLine();
                                Console.WriteLine("Enter admin last name:");
                                string adminLastName = Console.ReadLine();
                                Console.WriteLine("Enter admin username:"******"Enter admin password:"******"You added new Admin {adminName} , {adminLastName}");
                                Console.WriteLine($"-----------------------");
                                Console.WriteLine($"Do you want to add another Admin Y/N");
                                string addAdminCheck = Console.ReadLine().ToLower();
                                if (addAdminCheck == "n")
                                {
                                    Console.WriteLine("Thank you for adding new admin");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            while (addOption == "3")
                            {
                                //adding student
                                Console.WriteLine("Enter student first name:");
                                string studentName = Console.ReadLine();
                                Console.WriteLine("Enter student last name:");
                                string studentLastName = Console.ReadLine();
                                Console.WriteLine("Enter student username:"******"Enter student password:"******"Choose current subject: ");
                                foreach (var subject in Subjects)
                                {
                                    Console.WriteLine(subject.Name);
                                }

                                string  studentCurrentSubject  = Console.ReadLine();
                                Subject studentCurrentSubject1 = new Subject(studentCurrentSubject);
                                if (studentCurrentSubject == "C#")
                                {
                                    studentCurrentSubject1 = Subjects[0];
                                }
                                else if (studentCurrentSubject == "C#Advanced")
                                {
                                    studentCurrentSubject1 = Subjects[1];
                                }
                                else if (studentCurrentSubject == "JavaScript")
                                {
                                    studentCurrentSubject1 = Subjects[2];
                                }
                                else if (studentCurrentSubject == "HTML")
                                {
                                    studentCurrentSubject1 = Subjects[3];
                                }
                                else if (studentCurrentSubject == "JavaScriptAdvanced")
                                {
                                    studentCurrentSubject1 = Subjects[4];
                                }

                                Console.WriteLine("Add passed subject");


                                foreach (var subject in Subjects)
                                {
                                    Console.WriteLine(subject.Name);
                                }

                                string studentPassedSubject = Console.ReadLine();
                                Console.WriteLine("Add grade");
                                int studentPassedSubjectGrade = int.Parse(Console.ReadLine());
                                Dictionary <Subject, int> NewSubjectGrades1 = new Dictionary <Subject, int>();
                                if (studentPassedSubject == "C#")
                                {
                                    Dictionary <Subject, int> NewSubjectGrades = new Dictionary <Subject, int>()
                                    {
                                        [Subjects[0]] = studentPassedSubjectGrade,
                                    };
                                    NewSubjectGrades1 = NewSubjectGrades;
                                }
                                else if (studentPassedSubject == "C#Advanced")
                                {
                                    Dictionary <Subject, int> NewSubjectGrades = new Dictionary <Subject, int>()
                                    {
                                        [Subjects[1]] = studentPassedSubjectGrade,
                                    };
                                    NewSubjectGrades1 = NewSubjectGrades;
                                }
                                else if (studentPassedSubject == "JavaScript")
                                {
                                    Dictionary <Subject, int> NewSubjectGrades = new Dictionary <Subject, int>()
                                    {
                                        [Subjects[2]] = studentPassedSubjectGrade,
                                    };
                                    NewSubjectGrades1 = NewSubjectGrades;
                                }
                                else if (studentPassedSubject == "HTML")
                                {
                                    Dictionary <Subject, int> NewSubjectGrades = new Dictionary <Subject, int>()
                                    {
                                        [Subjects[3]] = studentPassedSubjectGrade,
                                    };
                                    NewSubjectGrades1 = NewSubjectGrades;
                                }
                                else if (studentPassedSubject == "JavaScriptAdvanced")
                                {
                                    Dictionary <Subject, int> NewSubjectGrades = new Dictionary <Subject, int>()
                                    {
                                        [Subjects[4]] = studentPassedSubjectGrade,
                                    };
                                    NewSubjectGrades1 = NewSubjectGrades;
                                }
                                else
                                {
                                    Console.WriteLine("Try again!");
                                }
                                users.Add(new Student(studentName, studentLastName, studentUsername, studentPassword, studentCurrentSubject1, NewSubjectGrades1));
                                Console.WriteLine($"You added new student {studentName} {studentLastName}");
                                Console.WriteLine($"-----------------------");
                                Console.WriteLine($"Do you want to add another student Y/N");
                                string addStudentCheck = Console.ReadLine().ToLower();
                                if (addStudentCheck == "n")
                                {
                                    Console.WriteLine("Thank you for adding student");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            Console.WriteLine($"-----------------------");
                            Console.WriteLine($"Do you want to choose another person(admin,trainer or student to add) Y/N");
                            string addMorePeople = Console.ReadLine().ToLower();
                            if (addMorePeople == "n")
                            {
                                Console.WriteLine("You choose not to add more people");
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        while (adminOption == "2")
                        {
                            Console.WriteLine("1.Remove trainer; 2.Remove admin; 3.Remove student");
                            string removeOption = Console.ReadLine();

                            while (removeOption == "1")
                            {
                                //remove trainer
                                Console.WriteLine("Please enter the username of the trainer you want to remove:");
                                foreach (var user in users.Where(u => u.Role == Role.Trainer))
                                {
                                    Console.WriteLine($"Trainer first name: {user.Firstname} , trainer last name: {user.Lastname}");
                                }
                                string username = Console.ReadLine();
                                Person found    = users.Where(x => x.Username == username).FirstOrDefault();
                                bool   removed  = users.Remove(found);
                                if (found != null && found.Role == Role.Trainer)
                                {
                                    users.Remove(users.Where(x => x.Username == username).FirstOrDefault());
                                }
                                if (removed)
                                {
                                    Console.WriteLine($"Trainer {found.Firstname} has been removed!");
                                }
                                else
                                {
                                    Console.WriteLine("There was no such user!");
                                    Console.WriteLine("Please try again");
                                    continue;
                                }
                                Console.WriteLine($"-----------------------");
                                Console.WriteLine($"Do you want to remove another trainer Y/N");
                                string removeTrainer = Console.ReadLine().ToLower();
                                if (removeTrainer == "n")
                                {
                                    Console.WriteLine("You choose not to remove more trainers");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            while (removeOption == "2")
                            {
                                //remove admin
                                Console.WriteLine("Please enter the username of the admin you want to remove:");
                                foreach (var user in users.Where(u => u.Role == Role.Admin))
                                {
                                    Console.WriteLine($"Admin first name: {user.Firstname} , Admin last name: {user.Lastname}");
                                }
                                string username = Console.ReadLine();
                                Person found    = users.Where(x => x.Username == username).FirstOrDefault();
                                bool   removed  = users.Remove(found);
                                if (found != null && found.Role == Role.Admin)
                                {
                                    users.Remove(users.Where(x => x.Username == username).FirstOrDefault());
                                }
                                if (removed)
                                {
                                    Console.WriteLine($"Admin {found.Firstname} has been removed!");
                                }
                                else
                                {
                                    Console.WriteLine("There was no such user!");
                                    Console.WriteLine("Please try again");
                                    continue;
                                }
                                Console.WriteLine($"-----------------------");
                                Console.WriteLine($"Do you want to remove another Admin Y/N");
                                string removeAdmin = Console.ReadLine().ToLower();
                                if (removeAdmin == "n")
                                {
                                    Console.WriteLine("You choose not to remove more admins");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            while (removeOption == "3")
                            {
                                //remove student
                                Console.WriteLine("Please enter the username of the student you want to remove:");
                                foreach (var user in users.Where(u => u.Role == Role.Student))
                                {
                                    Console.WriteLine($"Student first name: {user.Firstname} , Student last name: {user.Lastname}");
                                }
                                string username = Console.ReadLine();
                                Person found    = users.Where(x => x.Username == username).FirstOrDefault();
                                bool   removed  = users.Remove(found);
                                if (found != null && found.Role == Role.Student)
                                {
                                    users.Remove(users.Where(x => x.Username == username).FirstOrDefault());
                                }
                                if (removed)
                                {
                                    Console.WriteLine($"Student {found.Firstname} has been removed!");
                                }
                                else
                                {
                                    Console.WriteLine("There was no such user!");
                                    Console.WriteLine("Please try again");
                                    continue;
                                }

                                Console.WriteLine($"-----------------------");
                                Console.WriteLine($"Do you want to remove another student from this list: Y/N");
                                foreach (var user in users.Where(u => u.Role == Role.Student))
                                {
                                    Console.WriteLine($"Student first name: {user.Firstname} , Student last name: {user.Lastname}");
                                }
                                string removeStudent = Console.ReadLine().ToLower();
                                if (removeStudent == "n")
                                {
                                    Console.WriteLine("You choose not to remove more admins");
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            Console.WriteLine($"-----------------------");
                            Console.WriteLine($"Do you want to remove more people Y/N");
                            string removePerson = Console.ReadLine().ToLower();
                            if (removePerson == "n")
                            {
                                Console.WriteLine("You choose not to remove more people(admin,student or trainer)");
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        Console.WriteLine($"-----------------------");
                        Console.WriteLine($"Do you want to logout as admin Y/N");
                        string logOut = Console.ReadLine().ToLower();
                        if (logOut == "y")
                        {
                            Console.WriteLine("Please log in with another user");
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    #endregion
                    #region Trainer

                    if (User.Role == Role.Trainer)
                    {
                        Trainer trainer = (Trainer)User;
                        Console.WriteLine("Choose an option 1.List all students; 2.List all subjects");
                        string trainerChoice = Console.ReadLine();

                        while (trainerChoice == "1")
                        {
                            Console.WriteLine("Choose a student to see his grades");
                            foreach (var user in users.Where(u => u.Role == Role.Student))
                            {
                                Console.WriteLine($"Student first name: {user.Firstname} , Student last name: {user.Lastname}");
                            }
                            string studentName = Console.ReadLine();
                            var    found       = users.Where(x => x.Firstname == studentName).FirstOrDefault();

                            if (found != null && found.Role == Role.Student)
                            {
                                Student choosenStudent = (Student)users.Where(x => x.Firstname == studentName).FirstOrDefault();
                                Console.WriteLine(choosenStudent.GetInfo());
                            }
                            Console.WriteLine($"-----------------------");
                            Console.WriteLine($"Do you want to choose another student to see his grades Y/N");
                            string seeMoreStudents = Console.ReadLine().ToLower();
                            if (seeMoreStudents == "n")
                            {
                                Console.WriteLine("You choose not to see more students");
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        while (trainerChoice == "2")
                        {
                            //List all subjects
                            foreach (var subject in Subjects)
                            {
                                int studentsOfSubject = 0;
                                foreach (var user in users.Where(u => u.Role == Role.Student))
                                {
                                    Student currentStudent = (Student)user;
                                    if (subject == currentStudent.CurrentSubject)
                                    {
                                        studentsOfSubject += 1;
                                    }
                                }
                                Console.WriteLine($"Name of the subject: {subject.Name} ({studentsOfSubject}).");
                            }
                            Console.WriteLine($"-----------------------");
                            Console.WriteLine($"Do you want to go back one step  Y/N");
                            string back = Console.ReadLine().ToLower();
                            if (back == "y")
                            {
                                Console.WriteLine();
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        Console.WriteLine($"-----------------------");
                        Console.WriteLine($"Do you want to logout as trainer Y/N");
                        string logOut = Console.ReadLine().ToLower();
                        if (logOut == "y")
                        {
                            Console.WriteLine("Please log in with another user");
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    #endregion
                    #region User
                    if (User.Role == Role.Student)
                    {
                        Student student = (Student)User;
                        Console.WriteLine("1.Enroll; 2.List all grades");
                        string option = Console.ReadLine();

                        while (option == "1")
                        {
                            foreach (var subject in Subjects)
                            {
                                if (!student.Subjects.ContainsKey(subject))
                                {
                                    Console.WriteLine(subject.Name);
                                }
                            }

                            string chosenSubject = Console.ReadLine();
                            foreach (var subject in Subjects)
                            {
                                if (subject.Name == chosenSubject)
                                {
                                    Subject sub = Subjects.FirstOrDefault(x => x.Name == chosenSubject);
                                    student.Enroll(sub);
                                    //Subjects.Remove(subject);
                                    Console.WriteLine($"You enroled in {sub.Name}!");
                                }
                            }
                            Console.WriteLine($"-----------------------");
                            Console.WriteLine($"Do you want to enroll in more subjects Y/N");
                            string seeMoreStudents = Console.ReadLine().ToLower();
                            if (seeMoreStudents == "n")
                            {
                                Console.WriteLine("You choose not to enrol in more subjects");
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }

                        while (option == "2")
                        {
                            Console.WriteLine(student.GetInfo());
                            Console.WriteLine($"-----------------------");
                            Console.WriteLine($"do you want to choose different option Y/N");
                            string seeMoreStudents = Console.ReadLine().ToLower();
                            if (seeMoreStudents == "y")
                            {
                                Console.WriteLine("You choose to go back one step");
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        Console.WriteLine($"-----------------------");
                        Console.WriteLine($"Do you want to log out as student Y/N");
                        string studentlogout = Console.ReadLine().ToLower();
                        if (studentlogout == "y")
                        {
                            Console.WriteLine("You loged out as student.");
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    #endregion
                }
            }
        }
Ejemplo n.º 6
0
        public void Run()
        {
            var device = DeviceDescriptor.UseDefaultDevice();

            // 1. Generate Data
            int sampleSize        = 32;
            int nbDimensionsInput = 2; // 2 dimensions (age&tumorsize)
            int nbLabels          = 2; // l'output est un vecteur de probabilités qui doit sommer à 1. Si on ne met qu'une seule dimension de sortie, l'output sera toujours de 1.
            // on met donc deux dimension, une dimension 'vrai' et une dimension 'faux'. L'output sera du genre 0.25 vrai et 0.75 faux => total des poids = 1;
            // premier label = faux, second = vrai

            IEnumerable <DataPoint> data = GenerateData(sampleSize);

            //foreach (var pt in data)
            //    Debug.WriteLine($"{pt.Age};{pt.TumorSize};{(pt.HasCancer ? 1 : 0)}");

            Variable inputVariables = Variable.InputVariable(NDShape.CreateNDShape(new[] { nbDimensionsInput }), DataType.Double, "input");
            Variable expectedOutput = Variable.InputVariable(new int[] { nbLabels }, DataType.Double, "output");

            int nbHiddenLayers = 1;

            Function lastLayer = DefineNetwork(inputVariables, nbLabels, nbHiddenLayers, CNTKLib.Sigmoid);

            Function lossFunction      = CNTKLib.CrossEntropyWithSoftmax(lastLayer, expectedOutput);
            Function evalErrorFunction = CNTKLib.ClassificationError(lastLayer, expectedOutput);

            uint   minibatchSize = 25;
            double learningRate  = 0.5;
            TrainingParameterScheduleDouble learningRatePerSample = new TrainingParameterScheduleDouble(learningRate, minibatchSize);

            IList <Learner> parameterLearners = new List <Learner>()
            {
                Learner.SGDLearner(lastLayer.Parameters(), learningRatePerSample)
            };
            Trainer trainer = Trainer.CreateTrainer(lastLayer, lossFunction, evalErrorFunction, parameterLearners);

            double nbSamplesToUseForTraining = 20000;
            int    numMinibatchesToTrain     = (int)(nbSamplesToUseForTraining / (int)minibatchSize);

            // train the model
            for (int minibatchCount = 0; minibatchCount < numMinibatchesToTrain; minibatchCount++)
            {
                IEnumerable <DataPoint> trainingData = GenerateData((int)minibatchSize);

                List <double> minibatchInput  = new List <double>();
                List <double> minibatchOutput = new List <double>();
                foreach (DataPoint row in trainingData)
                {
                    minibatchInput.Add(row.Age);
                    minibatchInput.Add(row.TumorSize);
                    minibatchOutput.Add(row.HasCancer ? 0d : 1d);
                    minibatchOutput.Add(row.HasCancer ? 1d : 0d);
                }

                Value inputData  = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbDimensionsInput }), minibatchInput, device);
                Value outputData = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbLabels }), minibatchOutput, device);

                trainer.TrainMinibatch(new Dictionary <Variable, Value>()
                {
                    { inputVariables, inputData }, { expectedOutput, outputData }
                }, false, device);

                PrintTrainingProgress(trainer, minibatchCount);
            }

            // test
            {
                int testSize = 100;
                IEnumerable <DataPoint> trainingData = GenerateData(testSize);

                List <double> minibatchInput  = new List <double>();
                List <double> minibatchOutput = new List <double>();
                foreach (DataPoint row in trainingData)
                {
                    minibatchInput.Add(row.Age);
                    minibatchInput.Add(row.TumorSize);
                    minibatchOutput.Add(row.HasCancer ? 0d : 1d);
                    minibatchOutput.Add(row.HasCancer ? 1d : 0d);
                }

                Value inputData  = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbDimensionsInput }), minibatchInput, device);
                Value outputData = Value.CreateBatch <double>(NDShape.CreateNDShape(new int[] { nbLabels }), minibatchOutput, device);

                IList <IList <double> > expectedOneHot = outputData.GetDenseData <double>(lastLayer.Output);
                IList <int>             expectedLabels = expectedOneHot.Select(l => l.IndexOf(1.0d)).ToList();

                var outputDataMap = new Dictionary <Variable, Value>()
                {
                    { lastLayer.Output, null }
                };
                lastLayer.Evaluate(
                    new Dictionary <Variable, Value>()
                {
                    { inputVariables, inputData }
                },
                    outputDataMap,
                    device);

                Value outputValue = outputDataMap[lastLayer.Output];

                IList <IList <double> > actualLabelSoftMax = outputValue.GetDenseData <double>(lastLayer.Output);
                var actualLabels = actualLabelSoftMax.Select((IList <double> l) => l.IndexOf(l.Max())).ToList();
                int misMatches   = actualLabels.Zip(expectedLabels, (a, b) => a.Equals(b) ? 0 : 1).Sum();

                Debug.WriteLine($"Validating Model: Total Samples = {testSize}, Misclassify Count = {misMatches}");
            }
        }
Ejemplo n.º 7
0
        public void Run()
        {
            var device = DeviceDescriptor.UseDefaultDevice();

            var util = new Example_103_Util();

            // data
            string        trainImagesPath = "./Example_103/train-images-idx3-ubyte.gz";
            string        trainLabelsPath = "./Example_103/train-labels-idx1-ubyte.gz";
            List <byte[]> trainImages     = util.LoadImages(trainImagesPath);
            List <int>    trainLabels     = util.LoadLabels(trainLabelsPath);
            List <int[]>  trainLabels1Hot = trainLabels.Select(x => util.ConvertTo1Hot(x)).ToList();

            string        evelImagesPath = "./Example_103/t10k-images-idx3-ubyte.gz";
            string        evalLabelsPath = "./Example_103/t10k-labels-idx1-ubyte.gz";
            List <byte[]> evalImages     = util.LoadImages(evelImagesPath);
            List <int>    evalLabels     = util.LoadLabels(evalLabelsPath);
            List <int[]>  evalLabels1Hot = evalLabels.Select(x => util.ConvertTo1Hot(x)).ToList();

            // model

            int sampleSize = trainImages.Count;
            int nbLabels   = 10; // de 0 à 10

            Variable inputVariables = Variable.InputVariable(NDShape.CreateNDShape(new[] { 28, 28, 1 }), DataType.Double, "input");
            Variable expectedOutput = Variable.InputVariable(NDShape.CreateNDShape(new int[] { nbLabels }), DataType.Double, "output");

            var scaledInput = CNTKLib.ElementTimes(Constant.Scalar <double>(1.0 / 255.0, device), inputVariables);

            Function lastLayer = DefineModel_103D(util, nbLabels, scaledInput);

            Function lossFunction      = CNTKLib.CrossEntropyWithSoftmax(lastLayer, expectedOutput);
            Function evalErrorFunction = CNTKLib.ClassificationError(lastLayer, expectedOutput);

            // training

            Trainer trainer;
            {
                // define training

                uint   minibatchSize = 64;
                double learningRate  = 0.2;
                TrainingParameterScheduleDouble learningRatePerSample = new TrainingParameterScheduleDouble(learningRate, minibatchSize);
                List <Learner> parameterLearners = new List <Learner>()
                {
                    Learner.SGDLearner(lastLayer.Parameters(), learningRatePerSample)
                };
                trainer = Trainer.CreateTrainer(lastLayer, lossFunction, evalErrorFunction, parameterLearners);

                // run training

                int nbSamplesToUseForTraining = trainImages.Count;
                int numSweepsToTrainWith      = 10; // traduction de sweep ?
                int numMinibatchesToTrain     = nbSamplesToUseForTraining * numSweepsToTrainWith / (int)minibatchSize;

                var minibatchSource = new Example_103_MinibatchSource(inputVariables, trainImages, expectedOutput, trainLabels1Hot, nbSamplesToUseForTraining, numSweepsToTrainWith, minibatchSize, device);
                for (int minibatchCount = 0; minibatchCount < numMinibatchesToTrain; minibatchCount++)
                {
                    IDictionary <Variable, MinibatchData> data = minibatchSource.GetNextRandomMinibatch();
                    trainer.TrainMinibatch(data, device);
                    util.PrintTrainingProgress(trainer, minibatchCount);
                }
            }

            // evaluate
            {
                uint   testMinibatchSize     = 512;
                int    nbSamplesToTest       = evalImages.Count;
                int    numMinibatchesToTrain = nbSamplesToTest / (int)testMinibatchSize;
                double testResult            = 0;

                var minibatchSource = new Example_103_MinibatchSource(inputVariables, evalImages, expectedOutput, evalLabels1Hot, nbSamplesToTest, 1, testMinibatchSize, device);
                for (int minibatchCount = 0; minibatchCount < numMinibatchesToTrain; minibatchCount++)
                {
                    IDictionary <Variable, MinibatchData> data = minibatchSource.GetNextRandomMinibatch();

                    UnorderedMapVariableMinibatchData evalInput = new UnorderedMapVariableMinibatchData();
                    foreach (var row in data)
                    {
                        evalInput[row.Key] = row.Value;
                    }

                    double error = trainer.TestMinibatch(evalInput, device);
                    testResult += error;

                    //var z = CNTKLib.Softmax(lastLayer);
                    //var tOut = new Dictionary<Variable, Value>() { { z.Output, null } };

                    //z.Evaluate(
                    //    new Dictionary<Variable, Value>() { { inputVariables, data[inputVariables].data } },
                    //    tOut,
                    //    device
                    //    );

                    //Value outputValue = tOut[z.Output];
                    //IList<IList<double>> actualLabelSoftMax = outputValue.GetDenseData<double>(z.Output);
                    //var actualLabels = actualLabelSoftMax.Select((IList<double> l) => l.IndexOf(l.Max())).ToList();

                    //Value expectedOutputValue = data[expectedOutput].data;
                    //IList<IList<double>> expectedLabelsSoftmax = expectedOutputValue.GetDenseData<double>(z.Output);
                    //var expectedLabels = expectedLabelsSoftmax.Select((IList<double> l) => l.IndexOf(l.Max())).ToList();

                    //for(int i = 0; i < expectedLabels.Count; i++)
                    //{
                    //    if (actualLabels[i] != expectedLabels[i])
                    //    {
                    //        Debug.WriteLine($"{actualLabels[i]} {expectedLabels[i]}");
                    //    }
                    //}

                    //int misMatches = actualLabels.Zip(expectedLabels, (a, b) => a.Equals(b) ? 0 : 1).Sum();

                    Debug.WriteLine($"Average test error: {(testResult / (minibatchCount + 1)):p2}");
                }

                Debug.WriteLine($"Average test error: {(testResult / numMinibatchesToTrain):p2}");
            }
        }