Example #1
0
        public static dynamic NewConverter()
        {
            var converter = new PyConverter();

            using (Py.GIL())
            {
                //XIncref is needed, or keep the PyObject
                converter.Converters.Add(PythonEngine.Eval("int").Handle, (args) => { return(args.AsManagedObject(typeof(int))); });
                converter.Converters.Add(PythonEngine.Eval("str").Handle, (args) => { return(args.AsManagedObject(typeof(string))); });
                converter.Converters.Add(PythonEngine.Eval("float").Handle, (args) => { return(args.AsManagedObject(typeof(double))); });
                converter.Converters.Add(PythonEngine.Eval("bool").Handle, (args) => { return(args.AsManagedObject(typeof(bool))); });
                converter.Converters.Add(PythonEngine.Eval("list").Handle, (args) =>
                {
                    List <object> list = new List <object>();
                    for (int i = 0; i < args.Length(); i++)
                    {
                        dynamic newVal = converter.Convert(args[i]);
                        list.Add(newVal);
                    }
                    return(list);
                });
                converter.Converters.Add(PythonEngine.Eval("dict").Handle, (args) =>
                {
                    Dictionary <string, object> dict = new Dictionary <string, object>();
                    var dictionaryItems = args.InvokeMethod("items");
                    Console.WriteLine("dictionaryItems");
                    foreach (dynamic keyValue in dictionaryItems)
                    {
                        dynamic newKey   = converter.Convert(keyValue[0]);
                        dynamic newValue = converter.Convert(keyValue[1]);
                        dict.Add(newKey.ToString(), newValue);
                    }
                    return(dict);
                });
            }
            return(converter);
        }
        /// <summary>
        /// Key-Value : ProductId - Prediction Value (rate)
        /// </summary>
        /// <returns></returns>
        public Dictionary <int, double> GetPredictions()
        {
            try
            {
                using (Py.GIL())
                {
                    dynamic ev = getFeatures.Event2vec();
                    logger.Debug("Event vector:" + ev?.ToString());
                    Console.WriteLine("Event vector:" + ev);

                    //simulate a time now
                    int epoch1 = (int)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds + 1200;
                    Console.WriteLine("epoch:" + epoch1);
                    dynamic timenow1 = pythonModule.testtime(epoch1);
                    logger.Debug("Timenow1:" + timenow1?.ToString());
                    Console.WriteLine("Timenow1:" + timenow1);

                    dynamic td = getFeatures.get_timedelta();
                    logger.Debug(" Time delta" + td?.ToString());
                    Console.WriteLine("Time delta" + td);
                    // calling and showing fit parameters of the algorithm
                    dynamic W1 = pythonModule.W1;
                    logger.Debug("W1: " + W1?.ToString());
                    dynamic W2 = pythonModule.W2;
                    logger.Debug("W2: " + W2?.ToString());
                    dynamic W3 = pythonModule.W3;
                    logger.Debug("W3: " + W3?.ToString());

                    // importing the fit matrix ' item_context_pred" founded under python code
                    dynamic ict = pythonModule.item_context_pred;
                    logger.Debug("predicted context: " + ict?.ToString());

                    // importing the fit matrix ' Products" founded under python code
                    dynamic products = pythonModule.Products;
                    logger.Debug("Products: " + ict?.ToString());

                    // checking python feature engineering functions before fitting inputs to the model

                    // input derived from contexts
                    dynamic ctoi = pythonModule.Context2Item(ict);
                    logger.Debug("Sale probability for each item  according to the actual context: " + ctoi?.ToString());

                    // input derived from user profile
                    dynamic uti = pythonModule.User2Item(this.userProfile);
                    logger.Debug("Sale probability for each item  according to the user_profile: " + uti?.ToString());

                    // input derived from happening events
                    dynamic eti = pythonModule.Event2Item(ev);
                    logger.Debug("Sale probability for each item  according to happening event: " + eti?.ToString());
                    Console.WriteLine("Sale probability for each item  according to happening event: " + eti?.ToString());

                    // input derived from time delta
                    dynamic mah = pythonModule.Mah(td);
                    logger.Debug("Sale probability for each item  according to the visit duration of the client: " + mah?.ToString());
                    Console.WriteLine("Sale probability for each item  according to the visit duration of the client: " + mah?.ToString());


                    // putting all together and using the python class "Recommendation" to make predictions
                    dynamic rec = pythonModule.Recommendation(ict, products, userProfile, ev, td, W1, W2, W3);

                    dynamic pred;
                    if (UsedPredictionMode == PredictionMode.PredictionWithProductScoreOptimization)
                    {
                        logger.Debug("SCORE-BASED PREDICTION:");
                        pred = rec.get_prediction(out_format: "dict");// out_format: " dict" gives the output under a dictionary
                        Console.WriteLine("SCORE-BASED PREDICTION:");
                        Console.WriteLine(pred);
                        //dynamic predtodict = pred.to_dict();
                    }
                    else
                    {
                        logger.Debug("PRICE-BASED PREDICTION:");
                        pred = rec.get_optprediction();// out_format: " dict" gives the uoutput under a dictionary
                        Console.WriteLine("PRICE-BASED PREDICTION:");
                        Console.WriteLine(pred);
                        //dynamic predtodict = pred.to_dict();
                    }

                    if (pred != null)
                    {
                        logger.Debug(pred?.ToString());
                    }

                    var converter = PyConverter.NewConverter();                                 //create an instance of PyConverter, take from ConverteurPy.cs script
                    Dictionary <string, object> productNameAndScores = converter.Convert(pred); //b is a List of CLR objects

                    //
                    // Transform product Name into equivalent product Id:
                    //

                    Dictionary <int, double> productIdAndScores = new Dictionary <int, double>();
                    if (productNameAndScores != null)
                    {
                        using (ShopDBModel context = new ShopDBModel())
                        {
                            //List<ProductScore> productScores = productNameAndScores.Select(pns => new ProductScore { Name = pns.Key, Score = pns.Value, Id = 0 }).ToList();
                            //List<string> productNames = productScores.Select(ps => ps.Name).ToList();

                            //// Retrieve corresponding products from database:
                            //List<ProductScore> productsFromDB = context.Products.Where(p => productNames.Contains(p.Name)).Select(p2 => new ProductScore { Id = p2.ID, Name = p2.Name }).ToList();
                            //ProductScore currentProductScore = null;

                            //// Change product Name with product ID:
                            //foreach (KeyValuePair<string, double> kvp in productNameAndScores)
                            //{
                            //    currentProductScore = productsFromDB.FirstOrDefault(pfd => pfd.Name == kvp.Key);
                            //    if (currentProductScore == null)
                            //    {
                            //        continue;
                            //    }
                            //    productIdAndScores.Add(currentProductScore.Id, kvp.Value);
                            //}
                        }
                    }
                    return(productIdAndScores);
                }
            }
            catch (Exception ex)
            {
                logger.Error(nameof(GetPredictions), "Unable to compute user predictions", ex);
                return(null);
            }
        }