コード例 #1
0
        /// <summary>
        /// Updates the given chart with the specified linear regression.
        /// </summary>
        /// <param name="chart">A chart.</param>
        /// <param name="lr">Linear Regression.</param>
        /// <param name="predictorIndex">The predictor (independent) variable to plot on the x-axis.</param>
        /// <exception cref="InvalidArgumentException">
        /// Thrown if the given predictorIndex is outside the range of columns in lr.PredictorMatrix.
        /// </exception>
        /// <remarks>
        /// The multidimensional linear regression fit is plotted projected onto the plane of the specified 
        /// predictor variable.
        /// <br/>
        /// Titles are added only if chart does not currently contain any titles.
        /// <br/>
        /// The first two data series are replaced, or added if necessary.
        /// </remarks>
        public static void Update( ref ChartControl chart, LinearRegression lr, int predictorIndex )
        {
            if( predictorIndex < 0 || predictorIndex > lr.PredictorMatrix.Cols )
              {
            throw new Core.IndexOutOfRangeException( predictorIndex );
              }

              List<string> titles = new List<string>()
              {
            "LinearRegression",
              };
              string xTitle = "Independent Variable " + predictorIndex;
              string yTitle = "Dependent Variable";

              // create version of predictor matrix with all other columns zeroed out
              DoubleMatrix projection = new DoubleMatrix( lr.PredictorMatrix.Rows, lr.PredictorMatrix.Cols );
              projection[Slice.All, predictorIndex] = lr.PredictorMatrix.Col( predictorIndex );

              DoubleMatrix data = new DoubleMatrix( lr.NumberOfObservations, 3 );
              data[Slice.All, 0] = lr.PredictorMatrix.Col( predictorIndex );          // x
              data[Slice.All, 1] = lr.Observations;                                   // y
              data[Slice.All, 2] = lr.PredictedObservations( projection );            // y predicted

              data = NMathFunctions.SortByColumn( data, 0 );

              List<ChartSeries> series = new List<ChartSeries>()
              {
            BindXY( data.Col(0), data.Col(1), ChartSeriesType.Scatter, DefaultMarker ),

            // only necessary to plot endpoints of line
            BindXY( data.Col(0)[new Slice(0, 2, data.Rows - 1)], data.Col(2)[new Slice(0, 2, data.Rows - 1)], ChartSeriesType.Line, ChartSymbolShape.None )
              };
              series[0].Text = "Observed";
              series[1].Text = "Predicted";

              Update( ref chart, series, titles, xTitle, yTitle );
        }
コード例 #2
0
        /// <summary>
        /// Demonstrates linear reression in two dimensions.
        /// </summary>
        void LinearRegression()
        {
            // Set up example description
            nRichDescription.Text = "A linear regression model is computed from the sample data containing random normal noise. \n\nA point is then predicted from the model with a 95% confidence interval - meaning the predicted point is expected to lie within the confidence interval 95% of the time.";

            // First read in the independent (or predictor) values. This is a matrix
            // with one column and a row for each amounts measurement.
            DoubleVector raw_data = new DoubleVector(25, 0, 1);
            DoubleMatrix measurements = new DoubleMatrix(raw_data);

            // Next, read in the responses
            // Build a linear polynomial and add noise for interest
            RandomNumberGenerator rand = new RandGenNormal(0, noiselevel_);
            Polynomial poly = new Polynomial(new DoubleVector("0, 1"));
            DoubleVector responses = poly.Evaluate(raw_data) + new DoubleVector(raw_data.Length, rand); ;

            // Construct a linear regression. If we want our regression to calculate a
            // y-intercept we must send in true for the "addIntercept" parameter (the
            // third paramameter in the constructor).
            LinearRegression regression = new LinearRegression(measurements, responses, true);
            DoubleVector residues = regression.Residuals;

            // Use the linear regression class to make a prediction according to the model
            DoubleVector xvalues = new DoubleVector("30"); // Use the model to predict the observation at 30.
            Interval pi = regression.PredictionInterval(xvalues, 0.95);

            // Build some data points along the regression line for display
            DoubleMatrix abcissae = new DoubleMatrix(new DoubleVector(raw_data));
            DoubleVector predicted_ys = regression.PredictedObservations(abcissae);

            // Build the chart
            SetupChartLayout("Linear Regression");

            NChart chart = nChartControl1.Charts[0];

            SetupChartAxes(chart);

            // Set up the line series
            NLineSeries line = new NLineSeries();
            chart.Series.Add(line);

            // tell the series to regard the X values
            line.UseXValues = true;

            // no data labels
            line.DataLabelStyle.Visible = false;

            // Set the line color
            line.BorderStyle = new NStrokeStyle(2.0f, Color.Tomato);

            // name data set
            line.Name = "Linear Regression";

            // Add the the Linear Regression line data to the line series
            line.XValues.AddRange(abcissae.DataBlock.Data);
            line.Values.AddRange(predicted_ys.DataBlock.Data);

            // Draw the raw data points
            NPointSeries point = new NPointSeries();
            chart.Series.Add(point);

            point.UseXValues = true;
            point.DataLabelStyle.Visible = false;

            // Set the point appearance properties
            point.FillStyle = new NColorFillStyle(Color.SkyBlue);
            point.BorderStyle = new NStrokeStyle(1.0f,Color.DarkGray);
            point.PointShape = PointShape.Cross;
            point.Size = new NLength(6.0f);

            // Points must fit in the chart area
            point.InflateMargins = true;

            // Name point set
            point.Name = "Observations";

            // set the point data
            point.Values.AddRange(responses.DataBlock.Data);
            point.XValues.AddRange(measurements.DataBlock.Data);

            double m = (pi.Min + pi.Max) / 2.0;

            // Display the predicted value with an error bar series
            NErrorBarSeries predicted_points = new NErrorBarSeries();
            chart.Series.Add(predicted_points);
            predicted_points.Name = "Predicted Point";
            predicted_points.UseXValues = true;
            predicted_points.InflateMargins = true;
            predicted_points.FillStyle = new NColorFillStyle(Color.Crimson);
            predicted_points.BorderStyle = new NStrokeStyle(1.0f, Color.DarkGray);
            predicted_points.DataLabelStyle.Visible = false;
            predicted_points.MarkerStyle.Visible = true;
            predicted_points.MarkerStyle.FillStyle = new NColorFillStyle(Color.Crimson);
            predicted_points.MarkerStyle.BorderStyle = new NStrokeStyle(1.0f, Color.DarkGray);
            predicted_points.MarkerStyle.PointShape = PointShape.Bar;
            predicted_points.MarkerStyle.Width = new NLength(5);
            predicted_points.MarkerStyle.Height = new NLength(5);
            predicted_points.SizeY = new NLength(5);

            // Fill the data for the predicted point
            predicted_points.XValues.AddRange(xvalues.DataBlock.Data);
            predicted_points.Values.Add(m);
            predicted_points.UpperErrorsY.Add(pi.Max - m);
            predicted_points.LowerErrorsY.Add(m - pi.Min);

            // Create a label to display the predicted value
            NLabel label = new NLabel();
            label.BoundsMode = BoundsMode.None;
            label.ContentAlignment = ContentAlignment.BottomLeft;
            label.Location = new NPointL(
                new NLength(87, NRelativeUnit.ParentPercentage),
                new NLength(3, NRelativeUnit.ParentPercentage));

            label.TextStyle.TextFormat = TextFormat.XML;
            label.TextStyle.FontStyle = new NFontStyle("Arial", 9);
            label.TextStyle.StringFormatStyle.HorzAlign = Nevron.HorzAlign.Right;
            label.TextStyle.BackplaneStyle.Visible = true;
            label.TextStyle.BackplaneStyle.FillStyle = new NGradientFillStyle(GradientStyle.Horizontal, GradientVariant.Variant1, Color.FromArgb(130, 255, 255, 255), Color.FromArgb(130, 233, 233, 255));
            label.TextStyle.BackplaneStyle.Shape = BackplaneShape.SmoothEdgeRectangle;
            label.TextStyle.BackplaneStyle.StandardFrameStyle.InnerBorderColor = Color.White;
            label.Text = "<font color = 'crimson'>" + m.ToString("0.###") + "</font> - predicted value with 95% confidence interval";

            chart.ChildPanels.Add(label);

            nChartControl1.Refresh();
        }