Ejemplo n.º 1
0
        private Tuple <string, string> callPersonalizationService(HttpRequestFeatures httpRequestFeatures)
        {
            // Generate an ID to associate with the request.
            string eventId = Guid.NewGuid().ToString();

            // Get the actions list to choose from personalization with their features.
            IList <RankableAction> actions = GetActions();

            // Get context information from the user.
            string timeOfDayFeature = GetUsersTimeOfDay();
            string tasteFeature     = GetUsersTastePreference();

            // Create current context from user specified data.
            IList <object> currentContext = new List <object>()
            {
                new { time = timeOfDayFeature },
                new { taste = tasteFeature },
                new { httpRequestFeatures }
            };

            // Exclude an action for personalization ranking. This action will be held at its current position.
            IList <string> excludeActions = new List <string> {
                "juice"
            };

            // Rank the actions
            var          request  = new RankRequest(actions, currentContext, excludeActions, eventId);
            RankResponse response = client.Rank(request);

            string rankjson   = JsonConvert.SerializeObject(request, Formatting.Indented);
            string rewardjson = JsonConvert.SerializeObject(response, Formatting.Indented);

            return(Tuple.Create(rankjson, rewardjson));
        }
        public float SimulateEvent()
        {
            IList <RankableAction> actions = GetActions();

            int userId = 1;

            UserSimulator sim = new UserSimulator(userId, rand);

            var currentContext = GetSimulatedContext(userId);

            string eventId = Guid.NewGuid().ToString();

            var          request  = new RankRequest(actions, currentContext, null, eventId);
            RankResponse response = client.Rank(request);

            //RankResponse response = new RankResponse();

            float reward = 0f;

            string simulationResponse = sim.ReturnSimulatedAction(currentContext);

            Console.WriteLine("For Context {2}: Personalizer suggested {0}, simulation chose {1}", response.RewardActionId, simulationResponse, sim.GetKey((FoodContext)currentContext[0]));

            if (response.RewardActionId == simulationResponse)
            {
                reward = 1f;
            }

            // Send the reward for the action based on user response.
            client.Reward(response.EventId, new RewardRequest(reward));

            return(reward);
        }
Ejemplo n.º 3
0
        static void SimulateRandomUserPreferences()
        {
            for (int i = 0; i < 1000; i++)
            {
                Random random = new Random(DateTime.Now.Millisecond);

                IList <RankableAction> actions = GetActions();

                PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);

                IList <object> currentContext = new List <object>()
                {
                    new { professiom = random.Next(1, 5) },
                    new { preference = random.Next(1, 3) }
                };
                IList <string> excludeActions = new List <string> {
                    "http://codestories.gr/index.php/2018/10/21/297/"
                };

                // Generate an ID to associate with the request.
                string eventId = Guid.NewGuid().ToString();

                var          request  = new RankRequest(actions, currentContext, excludeActions, eventId);
                RankResponse response = client.Rank(request);
                client.Reward(response.EventId, new RewardRequest(random.Next(0, 2)));
            }
        }
        public IActionResult PostRank([FromBody] RankCategories rankCategories)
        {
            RankRequest  request = CreateRankRequest(rankCategories);
            RankResponse response;

            try
            {
                response = personalizerClient?.Rank(request);
                return(Ok(response));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        static void Main(string[] args)
        {
            int  iteration = 1;
            bool runLoop   = true;

            // Get the actions list to choose from personalizer with their features.
            IList <RankableAction> actions = GetActions();

            // Initialize Personalizer client.
            PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);

            do
            {
                Console.WriteLine("\nIteration: " + iteration++);

                // Get context information from the user.
                string timeOfDayFeature = GetUsersTimeOfDay();
                string tasteFeature     = GetUsersTastePreference();

                // Create current context from user specified data.
                IList <object> currentContext = new List <object>()
                {
                    new { time = timeOfDayFeature },
                    new { taste = tasteFeature }
                };

                // Exclude an action for personalizer ranking. This action will be held at its current position.
                IList <string> excludeActions = new List <string> {
                    "juice"
                };

                // Generate an ID to associate with the request.
                string eventId = Guid.NewGuid().ToString();

                // Rank the actions
                var          request  = new RankRequest(actions, currentContext, excludeActions, eventId);
                RankResponse response = client.Rank(request);

                Console.WriteLine("\nPersonalizer service thinks you would like to have: " + response.RewardActionId + ". Is this correct? (y/n)");

                float  reward = 0.0f;
                string answer = GetKey();

                if (answer == "Y")
                {
                    reward = 1;
                    Console.WriteLine("\nGreat! Enjoy your food.");
                }
                else if (answer == "N")
                {
                    reward = 0;
                    Console.WriteLine("\nYou didn't like the recommended food choice.");
                }
                else
                {
                    Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the recommended food choice.");
                }

                Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
                foreach (var rankedResponse in response.Ranking)
                {
                    Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability);
                }

                // Send the reward for the action based on user response.
                client.Reward(response.EventId, new RewardRequest(reward));

                Console.WriteLine("\nPress q to break, any other key to continue:");
                runLoop = !(GetKey() == "Q");
            } while (runLoop);
        }
Ejemplo n.º 6
0
        private static void Main(string[] args)
        {
            int  iteration = 1;
            bool runLoop   = true;

            // Initialize Personalization client.
            PersonalizerClient client = InitializePersonalizationClient(ServiceEndpoint);

            // Initialize the RSS Feed actions provider
            IActionProvider actionProvider = new RSSFeedActionProvider(new RSSParser
            {
                // Number of items to fetch while crawling the RSS feed
                ItemLimit = 2
            });

            // Initialize the Cognitive Services TextAnalyticsClient for featurizing the crawled action articles
            TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClient(new Uri(CognitiveTextAnalyticsEndpoint), new AzureKeyCredential(CognitiveTextAnalyticsAPIKey));

            // Initialize the Cognitive Text Analytics actions featurizer
            IActionFeaturizer actionFeaturizer = new CognitiveTextAnalyticsFeaturizer(textAnalyticsClient);

            var newsActions = new List <RankableAction>();

            foreach (var newsTopic in newsRSSFeeds)
            {
                Console.WriteLine($"Fetching Actions for: {newsTopic.Key} from {newsTopic.Value}");

                IList <CrawlAction> crawlActions = actionProvider.GetActionsAsync(newsTopic.Value).Result.ToList();
                Console.WriteLine($"Fetched {crawlActions.Count} actions");

                actionFeaturizer.FeaturizeActionsAsync(crawlActions).ConfigureAwait(false);
                Console.WriteLine($"Featurized actions for {newsTopic.Key}");

                // Generate a rankable action for each crawlAction and add the news topic as additional feature
                newsActions.AddRange(crawlActions.Select(a =>
                {
                    a.Features.Add(new { topic = newsTopic.Key });
                    return((RankableAction)a);
                }).ToList());
            }

            do
            {
                Console.WriteLine("Iteration: " + iteration++);

                // Get context information from the user.
                string username  = GetUserName();
                string timeOfDay = GetUsersTimeOfDay();
                string location  = GetLocation();

                // Create current context from user specified data.
                IList <object> currentContext = new List <object>()
                {
                    new { username },
                    new { timeOfDay },
                    new { location }
                };

                // Id to associate with the request
                string eventId = Guid.NewGuid().ToString();

                // Rank the actions
                var          request  = new RankRequest(newsActions, currentContext, null, eventId);
                RankResponse response = client.Rank(request);

                var recommendedAction = newsActions.Where(a => a.Id.Equals(response.RewardActionId)).FirstOrDefault();

                Console.WriteLine("Personalization service thinks you would like to read: ");
                Console.WriteLine("Id: " + recommendedAction.Id);

                JsonSerializerOptions options = new JsonSerializerOptions
                {
                    WriteIndented = true
                };
                Console.WriteLine("Features : " + JsonSerializer.Serialize(recommendedAction.Features, options));

                Console.WriteLine("Do you like this article ?(y/n)");

                float  reward = 0.0f;
                string answer = GetKey();
                if (answer == "Y")
                {
                    reward = 1;
                    Console.WriteLine("Great!");
                }
                else if (answer == "N")
                {
                    reward = 0;
                    Console.WriteLine("You didn't like the recommended news article.");
                }
                else
                {
                    Console.WriteLine("Entered choice is invalid. Service assumes that you didn't like the recommended news article.");
                }

                Console.WriteLine("Personalization service ranked the actions with the probabilities as below:");
                Console.WriteLine("{0, 10} {1, 0}", "Probability", "Id");
                var rankedResponses = response.Ranking.OrderByDescending(r => r.Probability);
                foreach (var rankedResponse in rankedResponses)
                {
                    Console.WriteLine("{0, 10} {1, 0}", rankedResponse.Probability, rankedResponse.Id);
                }

                // Send the reward for the action based on user response.
                client.Reward(response.EventId, new RewardRequest(reward));

                Console.WriteLine("Press q to break, any other key to continue:");
                runLoop = !(GetKey() == "Q");
            } while (runLoop);
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            //SimulateRandomUserPreferences();
            int  iteration = 1;
            bool runLoop   = true;

            // Get the actions list to choose from personalizer with their features.
            IList <RankableAction> actions = GetActions();

            // Initialize Personalizer client.
            PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);

            do
            {
                Console.WriteLine("\nIteration: " + iteration++);

                // Get context information from the user.
                string userProfession = GetUserProfession();
                string UserPreference = GetUsersPreference();

                // Create current context from user specified data.
                IList <object> currentContext = new List <object>()
                {
                    new { professiom = userProfession },
                    new { preference = UserPreference }
                };

                // Exclude an action for personalizer ranking. This action will be held at its current position.
                // This simulates a business rule to force the action "juice" to be ignored in the ranking.
                // As juice is excluded, the return of the API will always be with a probability of 0.
                IList <string> excludeActions = new List <string> {
                    "http://codestories.gr/index.php/2018/10/21/297/"
                };

                // Generate an ID to associate with the request.
                string eventId = Guid.NewGuid().ToString();

                // Rank the actions
                var          request  = new RankRequest(actions, currentContext, excludeActions, eventId);
                RankResponse response = client.Rank(request);

                Console.WriteLine("\nPersonalizer service thinks you should read this: " + response.RewardActionId + ". Is this correct? (y/n)");

                float  reward = 0.0f;
                string answer = GetKey();

                if (answer == "Y")
                {
                    reward = 1;
                    Console.WriteLine("\nGreat! Enjoy this article.");
                }
                else if (answer == "N")
                {
                    reward = 0;
                    Console.WriteLine("\nSorry, but try again we can do better!");
                }
                else
                {
                    Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the article.");
                }

                Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
                foreach (var rankedResponse in response.Ranking)
                {
                    Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability);
                }

                // Send the reward for the action based on user response.
                client.Reward(response.EventId, new RewardRequest(reward));

                Console.WriteLine("\nPress q to break, any other key to continue:");
                runLoop = !(GetKey() == "Q");
            } while (runLoop);
        }
        public static void Run([CosmosDBTrigger(
                                    databaseName: "changefeedlabdatabase",
                                    collectionName: "changefeeddemocollection",
                                    ConnectionStringSetting = "DBconnection",
                                    LeaseCollectionName = "leases")] IReadOnlyList <Document> input, ILogger log)
        {
            // Get the actions list to choose from personalizer with their features.
            IList <RankableAction> actions = GetActions();

            string             apikey   = "API key here";
            string             endpoint = "URL to cognitive service";
            PersonalizerClient client   = InitializePersonalizerClient(endpoint, apikey);

            // Iterate through modified documents from change feed.
            foreach (var doc in input)
            {
                if (doc.GetPropertyValue <string>("Action") == "Viewed")
                {
                    // Get context information.
                    string itemCategoryFeature = doc.GetPropertyValue <string>("Item");
                    if (itemCategoryFeature.StartsWith("W"))
                    {
                        itemCategoryFeature = "Women";
                    }
                    else
                    {
                        itemCategoryFeature = "Men";
                    }
                    string itemPriceFeature = doc.GetPropertyValue <string>("Price");

                    // Create current context from user specified data.
                    IList <object> currentContext = new List <object>()
                    {
                        new { category = itemCategoryFeature },
                        new { price = itemPriceFeature }
                    };

                    // Exclude an action for personalizer ranking. This action will be held at its current position.
                    IList <string> excludeActions = new List <string> {
                        "juice"
                    };

                    // Generate an ID to associate with the request.
                    string eventId = Guid.NewGuid().ToString();

                    // Rank the actions
                    var          request  = new RankRequest(actions, currentContext, excludeActions, eventId);
                    RankResponse response = client.Rank(request);

                    Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
                    foreach (var rankedResponse in response.Ranking)
                    {
                        log.LogInformation($"Id: {rankedResponse.Id}, Probability: {rankedResponse.Probability}");
                    }

                    // Send the reward for the action based on user response.
                    //client.Reward(response.EventId, new RewardRequest(reward));
                }

                /*
                 * "CartID": 4673,
                 *  "Action": "Purchased",
                 *  "Item": "Women's Flannel Shirt",
                 *  "Price": 19.99,
                 * */
            }
        }
 public RankResponse PostRank([FromBody] RankRequest rankRequest)
 {
     return(client.Rank(rankRequest));
 }
Ejemplo n.º 10
0
        // </classVariables>

        // <mainLoop>
        static void Main(string[] args)
        {
            int  iteration = 1;
            bool runLoop   = true;

            IList <PersonalizerRankableAction> actions = GetActions();

            PersonalizerClient client = InitializePersonalizerClient(new Uri(ServiceEndpoint));

            do
            {
                Console.WriteLine("\nIteration: " + iteration++);

                string timeOfDayFeature = GetUsersTimeOfDay();
                string tasteFeature     = GetUsersTastePreference();

                IList <object> currentContext = new List <object>()
                {
                    new { time = timeOfDayFeature },
                    new { taste = tasteFeature }
                };

                IList <string> excludeActions = new List <string> {
                    "juice"
                };

                string eventId = Guid.NewGuid().ToString();

                var rankOptions = new PersonalizerRankOptions(actions, currentContext, excludeActions, eventId);
                PersonalizerRankResult result = client.Rank(rankOptions);

                Console.WriteLine("\nPersonalizer service thinks you would like to have: " + result.RewardActionId + ". Is this correct? (y/n)");

                float  reward = 0.0f;
                string answer = GetKey();

                if (answer == "Y")
                {
                    reward = 1f;
                    Console.WriteLine("\nGreat! Enjoy your food.");
                }
                else if (answer == "N")
                {
                    reward = 0f;
                    Console.WriteLine("\nYou didn't like the recommended food choice.");
                }
                else
                {
                    Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the recommended food choice.");
                }

                Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
                foreach (var rankedResponse in result.Ranking)
                {
                    Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability);
                }

                client.Reward(result.EventId, reward);

                Console.WriteLine("\nPress q to break, any other key to continue:");
                runLoop = !(GetKey() == "Q");
            } while (runLoop);
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            int  iteration = 1;
            bool runLoop   = true;

            string csvPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string csvFile = System.IO.Path.Combine(csvPath, "PersonalizeDocs/Volkswagen-Models.csv");


            List <List <string> > csvFileRead = readCSV(csvFile);
            //printCSV(csvFileRead);

            // Get the actions list to choose from personalizer with their features.
            IList <RankableAction> actions = GetActions(csvFileRead);
            //foreach (RankableAction s in actions){ Console.WriteLine(s.Id);
            //foreach (object i in s.Features) Console.WriteLine(i);}

            // Initialize Personalizer client.
            PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);

            do
            {
                Console.WriteLine("\nIteration: " + iteration++);

                // Get context information from the user.
                string typeOfCarFeature   = GetUsersCarChoice();
                string personalityFeature = GetUsersCarFeatures();

                // Create current context from user specified data.
                string feat1 = csvFileRead[0][1];
                string feat2 = csvFileRead[0][2];

                //Console.WriteLine(feat1 + "  " + feat2);

                IList <object> currentContext = new List <object>()
                {
                    new { feat1 = typeOfCarFeature },
                    new { feat2 = personalityFeature }
                }; //to print
                   //foreach (object k in currentContext){Console.WriteLine(k);}

                // Exclude an action for personalizer ranking. This action will be held at its current position.
                IList <string> excludeActions = new List <string> {
                    "juice"
                };

                // Generate an ID to associate with the request.
                string eventId = Guid.NewGuid().ToString();

                // Rank the actions
                var request = new RankRequest(actions, currentContext, excludeActions, eventId);

                RankResponse response = client.Rank(request);

                Console.WriteLine("\nPersonalizer service thinks you would like to have: " + response.RewardActionId + ". Is this correct? (y/n)");

                float  reward = 0.0f;
                string answer = GetKey();

                if (answer == "Y")
                {
                    reward = 1;
                    Console.WriteLine("\nGreat! Enjoy your car.");
                }
                else if (answer == "N")
                {
                    reward = 0;
                    Console.WriteLine("\nYou didn't like the recommended car.");
                }
                else
                {
                    Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the recommended car.");
                }

                Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:");
                foreach (var rankedResponse in response.Ranking)
                {
                    Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability);
                }

                // Send the reward for the action based on user response.
                client.Reward(response.EventId, new RewardRequest(reward));

                Console.WriteLine("\nPress q to break, any other key to continue:");
                runLoop = !(GetKey() == "Q");
            } while (runLoop);
        }