Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            //STEP 1: Create MLContext to be shared across the model creation workflow objects
            MLContext mlcontext = new MLContext();

            //STEP 2: Read the training data which will be used to train the movie recommendation model

            IDataView trainingDataView = mlcontext.Data.LoadFromTextFile <MovieRating>(TrainingDataLocation, hasHeader: true, separatorChar: ',');

            //STEP 3: Transform your data by encoding the two features userId and movieID. These encoded features will be provided as input
            //        to our MatrixFactorizationTrainer.
            var dataProcessingPipeline = mlcontext.Transforms.Conversion.MapValueToKey(outputColumnName: "userIdEncoded", inputColumnName: nameof(MovieRating.userId))
                                         .Append(mlcontext.Transforms.Conversion.MapValueToKey(outputColumnName: "movieIdEncoded", inputColumnName: nameof(MovieRating.movieId)));

            //Specify the options for MatrixFactorization trainer
            MatrixFactorizationTrainer.Options options = new MatrixFactorizationTrainer.Options();
            options.MatrixColumnIndexColumnName = "userIdEncoded";
            options.MatrixRowIndexColumnName    = "movieIdEncoded";
            options.LabelColumnName             = "Label";
            options.NumberOfIterations          = 20;
            options.ApproximationRank           = 100;

            //STEP 4: Create the training pipeline
            var trainingPipeLine = dataProcessingPipeline.Append(mlcontext.Recommendation().Trainers.MatrixFactorization(options));

            //STEP 5: Train the model fitting to the DataSet
            Console.WriteLine("=============== Training the model ===============");
            ITransformer model = trainingPipeLine.Fit(trainingDataView);

            //STEP 6: Evaluate the model performance
            Console.WriteLine("=============== Evaluating the model ===============");
            IDataView testDataView = mlcontext.Data.LoadFromTextFile <MovieRating>(TestDataLocation, hasHeader: true, separatorChar: ',');
            var       prediction   = model.Transform(testDataView);
            var       metrics      = mlcontext.Regression.Evaluate(prediction, labelColumnName: "Label", scoreColumnName: "Score");

            Console.WriteLine("The model evaluation metrics RootMeanSquaredError:" + metrics.RootMeanSquaredError);

            //STEP 7:  Try/test a single prediction by predicting a single movie rating for a specific user
            var predictionengine = mlcontext.Model.CreatePredictionEngine <MovieRating, MovieRatingPrediction>(model);
            /* Make a single movie rating prediction, the scores are for a particular user and will range from 1 - 5.*/
            var movieratingprediction = predictionengine.Predict(
                new MovieRating()
            {
                userId  = predictionuserId,
                movieId = predictionmovieId
            }
                );

            Movie movieService = new Movie();

            Console.WriteLine(" movie rating prediction (1 - 5 stars) for movie:" + movieService.Get(predictionmovieId).movieTitle + " is:" + Math.Round(movieratingprediction.Score, 1));

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadLine();
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            //STEP 1: Create MLContext to be shared across the model creation workflow objects
            var mlcontext = new MLContext();

            //STEP 2: Create a reader by defining the schema for reading the movie recommendation datasets
            var reader = mlcontext.Data.CreateTextReader(new TextLoader.Arguments()
            {
                Separator = ",",
                HasHeader = true,
                Column    = new[]
                {
                    new TextLoader.Column("userId", DataKind.R4, 0),
                    new TextLoader.Column("movieId", DataKind.R4, 1),
                    new TextLoader.Column("Label", DataKind.R4, 2)
                }
            });

            //STEP 3: Read the training data which will be used to train the movie recommendation model
            IDataView trainingDataView = reader.Read(TrainingDataLocation);

            //STEP 4: Transform your data by encoding the two features userId and movieID. These encoded features will be provided as input
            //        to our MatrixFactorizationTrainer.
            var pipeline = mlcontext.Transforms.Conversion.MapValueToKey("userId", "userIdEncoded")
                           .Append(mlcontext.Transforms.Conversion.MapValueToKey("movieId", "movieIdEncoded"))
                           .Append(mlcontext.Recommendation().Trainers.MatrixFactorization("userIdEncoded", "movieIdEncoded", "Label",
                                                                                           advancedSettings: s => { s.NumIterations = 20; s.K = 100; }));

            //STEP 5: Train the model fitting to the DataSet
            Console.WriteLine("=============== Training the model ===============");
            var model = pipeline.Fit(trainingDataView);

            //STEP 6: Evaluate the model performance
            Console.WriteLine("=============== Evaluating the model ===============");
            IDataView testDataView = reader.Read(TestDataLocation);
            var       prediction   = model.Transform(testDataView);
            var       metrics      = mlcontext.Regression.Evaluate(prediction, label: "Label", score: "Score");
            //Console.WriteLine("The model evaluation metrics rms:" + Math.Round(float.Parse(metrics.Rms.ToString()), 1));


            //STEP 7:  Try/test a single prediction by predicting a single movie rating for a specific user
            var predictionengine = model.CreatePredictionEngine <MovieRating, MovieRatingPrediction>(mlcontext);

            /* Make a single movie rating prediction, the scores are for a particular user and will range from 1 - 5.
             * The higher the score the higher the likelyhood of a user liking a particular movie.
             * You can recommend a movie to a user if say rating > 3.5.*/
            var movieratingprediction = predictionengine.Predict(
                new MovieRating()
            {
                //Example rating prediction for userId = 6, movieId = 10 (GoldenEye)
                userId  = predictionuserId,
                movieId = predictionmovieId
            }
                );

            Movie movieService = new Movie();

            Console.WriteLine("For userId:" + predictionuserId + " movie rating prediction (1 - 5 stars) for movie:" + movieService.Get(predictionmovieId).movieTitle + " is:" + Math.Round(movieratingprediction.Score, 1));
        }
        static void Main(string[] args)
        {
            //STEP 1: Create MLContext to be shared across the model creation workflow objects
            MLContext mlcontext = new MLContext();

            //STEP 2: Read the training data which will be used to train the movie recommendation model
            //The schema for training data is defined by type 'TInput' in ReadFromTextFile<TInput>() method.
            IDataView trainingDataView = mlcontext.Data.ReadFromTextFile <MovieRating>(TrainingDataLocation, hasHeader: true, separatorChar: ',');

            //STEP 3: Transform your data by encoding the two features userId and movieID. These encoded features will be provided as input
            //        to our MatrixFactorizationTrainer.
            var dataProcessingPipeline = mlcontext.Transforms.Conversion.MapValueToKey(outputColumnName: userIdEncoded, inputColumnName: nameof(MovieRating.userId))
                                         .Append(mlcontext.Transforms.Conversion.MapValueToKey(outputColumnName: movieIdEncoded, inputColumnName: nameof(MovieRating.movieId)));

            //Specify the options for MatrixFactorization trainer
            MatrixFactorizationTrainer.Options options = new MatrixFactorizationTrainer.Options();
            options.MatrixColumnIndexColumnName = userIdEncoded;
            options.MatrixRowIndexColumnName    = movieIdEncoded;
            options.LabelColumnName             = DefaultColumnNames.Label;
            options.NumIterations = 20;
            options.K             = 100;

            //STEP 4: Create the training pipeline
            var trainingPipeLine = dataProcessingPipeline.Append(mlcontext.Recommendation().Trainers.MatrixFactorization(options));

            //STEP 5: Train the model fitting to the DataSet
            Console.WriteLine("=============== Training the model ===============");
            ITransformer model = trainingPipeLine.Fit(trainingDataView);

            //STEP 6: Evaluate the model performance
            Console.WriteLine("=============== Evaluating the model ===============");
            IDataView testDataView = mlcontext.Data.ReadFromTextFile <MovieRating>(TestDataLocation, hasHeader: true, separatorChar: ',');
            var       prediction   = model.Transform(testDataView);
            var       metrics      = mlcontext.Regression.Evaluate(prediction, label: DefaultColumnNames.Label, score: DefaultColumnNames.Score);

            Console.WriteLine("The model evaluation metrics rms:" + metrics.Rms);

            //STEP 7:  Try/test a single prediction by predicting a single movie rating for a specific user
            var predictionengine = model.CreatePredictionEngine <MovieRating, MovieRatingPrediction>(mlcontext);

            /* Make a single movie rating prediction, the scores are for a particular user and will range from 1 - 5.
             * The higher the score the higher the likelyhood of a user liking a particular movie.
             * You can recommend a movie to a user if say rating > 3.5.*/
            var movieratingprediction = predictionengine.Predict(
                new MovieRating()
            {
                //Example rating prediction for userId = 6, movieId = 10 (GoldenEye)
                userId  = predictionuserId,
                movieId = predictionmovieId
            }
                );

            Movie movieService = new Movie();

            Console.WriteLine("For userId:" + predictionuserId + " movie rating prediction (1 - 5 stars) for movie:" + movieService.Get(predictionmovieId).movieTitle + " is:" + Math.Round(movieratingprediction.Score, 1));

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadLine();
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            var mlcontext = new MLContext();

            #region build_model
            var reader = mlcontext.Data.CreateTextReader(new TextLoader.Arguments()
            {
                Separator = ",",
                HasHeader = true,
                Column    = new[]
                {
                    new TextLoader.Column("userId", DataKind.R4, 0),
                    new TextLoader.Column("movieId", DataKind.R4, 1),
                    new TextLoader.Column("Label", DataKind.R4, 2)
                }
            });

            var trainingDataView = reader.Read(TrainingDataLocation);

            var pipeline = mlcontext.Transforms.Conversion.MapValueToKey("userId", "userIdEncoded")
                           .Append(mlcontext.Transforms.Conversion.MapValueToKey("movieId", "movieIdEncoded"))
                           .Append(mlcontext.Recommendation().Trainers.MatrixFactorization("userIdEncoded", "movieIdEncoded", "Label", advancedSettings: s => { s.NumIterations = 20; s.K = 100; }));

            #endregion


            Console.WriteLine("=============== Training the model ===============");

            #region train_model
            var model = pipeline.Fit(trainingDataView);
            #endregion


            Console.WriteLine("=============== Evaluating the model ===============");

            #region evaluate_model
            var testDataView = reader.Read(TestDataLocation);
            var prediction   = model.Transform(testDataView);
            var metrics      = mlcontext.Regression.Evaluate(prediction, label: "Label", score: "Score");
            Console.WriteLine($"The model evaluation metrics rms: {Math.Round(metrics.Rms, 1)}");
            #endregion


            #region prediction

            var userId  = 6;
            var movieId = 10;

            var predictionengine = model.CreatePredictionEngine <MovieRating, MovieRatingPrediction>(mlcontext);

            /* Make a single movie rating prediction, the scores are for a particular user and will range from 1 - 5.
             * The higher the score the higher the likelihood of a user liking a particular movie.
             * You can recommend a movie to a user if say rating > 3.5.*/
            var movieratingprediction = predictionengine.Predict(
                new MovieRating()
            {
                //Example rating prediction for userId = 6, movieId = 10 (GoldenEye)
                userId  = userId,
                movieId = movieId
            }
                );

            var movieService = new Movie();
            Console.WriteLine($"For userId: {userId} movie rating prediction (1 - 5 stars) for movie: {movieService.Get(movieId).movieTitle} is: {Math.Round(movieratingprediction.Score, 0, MidpointRounding.ToEven)}");
            #endregion
        }