ML.NET预测灯每周使用时间序列或回归打开和关闭

问题描述

问题:我的数据具有灯光ID,并且在打开特定ID的灯光时会捕获数据。现在,下一步是尝试找出将来某个特定星期将打开哪些灯。谁能让我知道如何使用时间序列或回归进行此操作? link to the data

我需要预测的是像布尔值一样的开或关。以下是数据的关键:以下是我基于this ml github sample

使用的代码


灯光ID:这是一个ID为
的灯光广告 LightDate::这是在2 n个半年中每周捕获一次的数据
OnOff::如果特定ID的灯在该时间点亮或灭,则为1且为0时熄灭
WeightByMonth::由于每周一次捕获数据,该月最大亮灯次数只能是4。
WeightByYear::该年灯亮了多少次
TotalWeightOverTheYears:捕获的整个数据点亮了多少次

公共类LightSeriesModelHelper { /// ///使用带有SSA的时间序列预测(单光谱分析)来预测打开或关闭时的未来光。 /// /// ML.NET上下文。 ///预测的每个光源的预测文件(模型文件)。 ///用于保存文件每个光源的路径。 ///从数据库中获取 ///将用于在该灯光ID上进行预测的特定灯光ID的所有灯光统计信息的列表 公共静态无效PerformTimeSeriesForecasting(MLContext mlContext,字符串dataPath,ApplicationDbContext dbContext,int lightID,List LightsMLDataModelStats,字符串模型文件夹) { Console.WriteLine(“ ===============预测===============); ForecastProductUnits(mlContext,lightID,dataPath,dbContext,LightsMLDataModelStats,modelfolder); }

    /// <summary>
    /// Fit and save checkpoint of the model for predicting future LIGHT ONs
    /// </summary>
    /// <param name="mlContext">ML.NET context.</param>
    /// <param name="lightID">Id of the light series to forecast.</param>
    /// <param name="dataPath">Input data file path.</param>
    private static void ForecastProductUnits(MLContext mlContext,int lightID,string dataPath,ApplicationDbContext dbContext,List<LightsMLDataModel> LightsMLDataModelStats,string modelfolder)
    {
        //var productModelPath = $"product{player.id}_month_timeSeriesSSA.zip";
        string fileName = $"{lightID}_tPredictiveModel.zip";
        var productModelPath = $"{dataPath}/{fileName}";

        if (File.Exists(productModelPath))
        {
            File.Delete(productModelPath);
        }

        IDataView productDataView = LoadData(mlContext,lightID,dataPath,dbContext,LightsMLDataModelStats);
        var singleProductDataSeries = mlContext.Data.CreateEnumerable<LightsMLDataModel>(productDataView,false).OrderBy(p => p.LightDate);
        LightsMLDataModel lastMonthProductData = singleProductDataSeries.Last();
        FitAndSaveModel(mlContext,productDataView,productModelPath,fileName,modelfolder);
        TestPrediction(mlContext,lastMonthProductData,LightsMLDataModelStats);
    }

    /// <summary>
    /// Loads the monthly product data series for a product with the specified id.
    /// </summary>
    /// <param name="mlContext">ML.NET context.</param>
    /// <param name="lightID">light id.</param>
    /// <param name="dataPath">Input data file path.</param>
    private static IDataView LoadData(MLContext mlContext,float lightID,List<LightsMLDataModel> LightsMLDataModelStats)
    {

        IDataView allProductsDataView = mlContext.Data.LoadFromEnumerable<LightsMLDataModel>(LightsMLDataModelStats);


        IDataView productDataView = mlContext.Data.FilterRowsByColumn(allProductsDataView,"LightID",lightID + 1);

        return productDataView;
    }

    /// <summary>
    /// Build model for predicting next month's product unit sales using time series forecasting.
    /// </summary>
    /// <param name="mlContext">ML.NET context.</param>
    /// <param name="productDataSeries">ML.NET IDataView representing the loaded product data series.</param>
    /// <param name="outputModelPath">Model path.</param>
    private static void FitAndSaveModel(MLContext mlContext,IDataView productDataSeries,string outputModelPath,string filename,string modelfolder)
    {
        ConsoleWriteHeader("Fitting product forecasting Time Series model");

        int numSeriesDataPoints = 138; //The underlying data has a total of 34 months worth of data for each product

        IEstimator<ITransformer> forecastEstimator = mlContext.Forecasting.ForecastBySsa(
              outputColumnName: nameof(LightsTimeSeriesPrediction.ForecastedLightOnOrOff),inputColumnName: nameof(LightsMLDataModel.OnOff),// This is the column being forecasted.
              windowSize: 2,seriesLength: 52,// This parameter specifies the number of data points that are used when performing a forecast. is 52
              trainSize: numSeriesDataPoints,// This parameter specifies the total number of data points in the input time series,starting from the beginning.
              horizon: 2,// Indicates the number of values to forecast; 2 indicates that the next 2 months of product units will be forecasted.
              confidenceLevel: 0.95f,// Indicates the likelihood the real observed value will fall within the specified interval bounds.
              confidenceLowerBoundColumn: nameof(LightsTimeSeriesPrediction.ConfidenceLowerBound),//This is the name of the column that will be used to store the lower interval bound for each forecasted value.
              confidenceUpperBoundColumn: nameof(LightsTimeSeriesPrediction.ConfidenceUpperBound)); //This is the name of the column that will be used to store the upper interval bound for each forecasted value.

        // Fit the forecasting model to the specified product's data series.
        ITransformer forecastTransformer = forecastEstimator.Fit(productDataSeries);

        // Create the forecast engine used for creating predictions.
        TimeSeriesPredictionEngine<LightsMLDataModel,LightsTimeSeriesPrediction> forecastEngine = forecastTransformer.CreateTimeSeriesEngine<LightsMLDataModel,LightsTimeSeriesPrediction>(mlContext);

        // Save the forecasting model so that it can be loaded within an end-user app.
        forecastEngine.CheckPoint(mlContext,outputModelPath);
        string folderrr = $"{modelfolder}/";
    }

    /// <summary>
    /// Predict samples using saved model.
    /// </summary>
    /// <param name="mlContext">ML.NET context.</param>
    /// <param name="lastMonthProductData">The last month of product data in the monthly data series.</param>
    /// <param name="outputModelPath">Model file path</param>
    private static void TestPrediction(MLContext mlContext,LightsMLDataModel lastMonthWeeksData,List<LightsMLDataModel> LightsMLDataModelStats)
    {
        ConsoleWriteHeader("Testing product unit sales forecast Time Series model");

        // Load the forecast engine that has been previously saved.
        ITransformer forecaster;
        using (var file = File.OpenRead(outputModelPath))
        {
            forecaster = mlContext.Model.Load(file,out DataViewSchema schema);
        }

        // We must create a new prediction engine from the persisted model.
        TimeSeriesPredictionEngine<LightsMLDataModel,LightsTimeSeriesPrediction> forecastEngine = forecaster.CreateTimeSeriesEngine<LightsMLDataModel,LightsTimeSeriesPrediction>(mlContext);

       
        Console.WriteLine("\n** Original prediction **");
        LightsTimeSeriesPrediction originalPrediction = forecastEngine.Predict();

        Console.WriteLine($"Product: {lastMonthWeeksData.LightID},Date {lastMonthWeeksData.LightDate} " +
            $"- Real Value outcome: {lastMonthWeeksData.NextOn},Forecast Prediction : {originalPrediction.ForecastedLightOnOrOff[0]}");

        // Get the first forecasted month's confidence interval bounds.
        Console.WriteLine($"Confidence interval: [{originalPrediction.ConfidenceLowerBound[0]} - {originalPrediction.ConfidenceUpperBound[0]}]\n");

        // Get the units of the second forecasted week.
        Console.WriteLine($"Product: {lastMonthWeeksData.LightID},Date {lastMonthWeeksData.LightDate.AddDays(7)} " +
            $"Forecast (units): {originalPrediction.ForecastedLightOnOrOff[1]}");

        // Get the second forecasted month's confidence interval bounds.
        Console.WriteLine($"Confidence interval: [{originalPrediction.ConfidenceLowerBound[1]} - {originalPrediction.ConfidenceUpperBound[1]}]\n");

        // Update the forecasting model with the next weeks's actual light data to get an updated prediction; this time,only forecast product sales for 1 week ahead.
        Console.WriteLine("** Updated prediction **");

        LightsTimeSeriesPrediction updatedPrediction = forecastEngine.Predict(LightsMLDataModelStats.LastOrDefault(),horizon: 1);
        // Save a checkpoint of the forecasting model.
        forecastEngine.CheckPoint(mlContext,outputModelPath);

        // Get the units of the updated forecast.
        Console.WriteLine($"Product: {lastMonthWeeksData.LightID},Date {lastMonthWeeksData.LightDate.AddDays(7)} " +
            $"Forecast (units): {updatedPrediction.ForecastedLightOnOrOff[0]}");

        // Get the updated forecast's confidence interval bounds.
        Console.WriteLine($"Confidence interval: [{updatedPrediction.ConfidenceLowerBound[0]} - {updatedPrediction.ConfidenceUpperBound[0]}]\n");



    }



    public static double ConvertGivenMins(string[] mins)
    {
        List<double> dmins = new List<double>();
        foreach (var min in mins)
        {
            string fixedMins = min.Replace(":",".");
            double mymin = double.TryParse(fixedMins,out double fixedmins) ? fixedmins : 0;
            dmins.Add(mymin);
        }

        var minsResult = Math.Round(dmins.Average(),2);
        return minsResult;
    }

    public class LightsMLDataModel
    {
        public float LightID { get; set; }
        public float OnOff { get; set; }
        public float PrevOn { get; set; }
        public float NextOn { get; set; }
        public float WeightByMonth { get; set; }
        public float WeightByYear { get; set; }
        public float TotalWeightOverTheYears { get; set; }
        public DateTime LightDate { get; set; }
        public float WeekOfYear { get; set; }
    }

    public class LightsTimeSeriesPrediction
    {
        public float[] ForecastedLightOnOrOff { get; set; }

        public float[] ConfidenceLowerBound { get; set; }

        public float[] ConfidenceUpperBound { get; set; }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...