Tensorflow Forecast Example

by sberube

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Time Series Forecasting Example</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
</head>
<body>
  <h1>Time Series Forecasting Example</h1>
  <div id="chart" style="width: 800px; height: 400px;"></div>
  <div id="output"></div>

  <script>
    // Generate dummy data for May
    const knownData = Array.from({ length: 31 }, (_, i) => {
      const date = new Date(2023, 4, i + 1); // Months are 0-indexed in JS
      return {
        date: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
        value: Math.floor(Math.random() * 20 + 10) // Random values between 10 and 30
      };
    });

    // Prepare input and output arrays
    const input = knownData.map(({ value }) => value);
    const output = knownData.map(({ value }) => value).slice(1).concat([0]); // add 0 as last value for output

    // Initialize ECharts instance
    const chart = echarts.init(document.getElementById('chart'));

    // Create options for the chart
    const options = {
      title: { text: 'Time Series Forecasting' },
      tooltip: { trigger: 'axis' },
      legend: { data: ['Actual Spend', 'Forecasted Spend'] },
      xAxis: { type: 'time' },
      yAxis: { type: 'value' },
      series: [
        { name: 'Actual Spend', type: 'line', data: knownData.map(d => [d.date, d.value]) },
        { name: 'Forecasted Spend', type: 'line', data: [] }
      ]
    };

    // Set options to the chart
    chart.setOption(options);

    // Format date as YYYY-MM-DD
    function formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }

    // Train the model and generate a forecast
   ...