/// <summary>
    /// Creates the Scatterplots in a subroutine, one per frame.
    /// This was done to keep the programm from freezen when creating
    /// the Scatterplots.
    /// </summary>
    /// <param name="scatterplotPrefab"></param>
    /// <param name="dataSource"></param>
    /// <param name="dimCombinations"></param>
    /// <param name="matrixWidth"></param>
    /// <returns></returns>
    IEnumerator CreateScatterplotsCoroutine(GameObject scatterplotPrefab, CSVDataSource dataSource, int[,] dimCombinations, int matrixWidth)
    {
        for (int i = 0; dimCombinations.GetLength(0) > i; i++)
        {
            //Debug.Log("creations scatterplot" + i);
            int matrixPosX = i % matrixWidth * 2;
            int matrixPosZ = i / matrixWidth * 2;
            int xDim       = dimCombinations[i, 0];
            int yDim       = dimCombinations[i, 1];
            int zDim       = dimCombinations[i, 2];

            Transform tempTransform = transform;
            tempTransform.position += new Vector3(0f, 0.02f, 0f);

            Scatterplot scatterplot = Instantiate(scatterplotPrefab, tempTransform).GetComponent <Scatterplot>();
            scatterplot.Initialize(dataSource, matrixPosX, matrixPosZ, pointSize, xDim, yDim, zDim, bigScatterplot);
            scatterplots[i] = scatterplot;

            if (bigScatterplot)
            {
                scatterplot.transform.localScale += Vector3.one;
            }
            else
            {
                scatterplot.transform.localScale -= Vector3.one / 2;
            }

            yield return(null);
        }
    }
Exemple #2
0
        private static ScatterplotBox show(Scatterplot scatterplot)
        {
            ScatterplotBox form       = null;
            Thread         formThread = null;

            AutoResetEvent stopWaitHandle = new AutoResetEvent(false);

            formThread = new Thread(() =>
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // Show control in a form
                form            = new ScatterplotBox();
                form.Text       = scatterplot.Title;
                form.formThread = formThread;
                form.scatterplotView1.Scatterplot = scatterplot;

                stopWaitHandle.Set();

                Application.Run(form);
            });

            formThread.SetApartmentState(ApartmentState.STA);

            formThread.Start();

            stopWaitHandle.WaitOne();

            return(form);
        }
Exemple #3
0
        public void PlotTrainingAndValidationCurves(
            IEnumerable <double> errors,
            IEnumerable <double> validationErrors,
            int epochCount)
        {
            IEnumerable <double> tmp = Enumerable
                                       .Range(1, epochCount)
                                       .Select(v => (double)v)
                                       .ToList();

            double[] x = tmp.Concat(tmp).ToArray();
            double[] y = errors.Concat(validationErrors).ToArray();
            int[]    z = Enumerable
                         .Repeat(1, epochCount)
                         .Concat(Enumerable.Repeat(2, epochCount))
                         .ToArray();

            Scatterplot plot = new Scatterplot(
                TrainingAndValidationPlotResources.Title,
                TrainingAndValidationPlotResources.XAxisTitle,
                TrainingAndValidationPlotResources.YAxisTitle);

            plot.Compute(x, y, z);

            ScatterplotBox.Show(plot);
        }
Exemple #4
0
        private static ScatterplotBox show(String title, Func <double, double> function, double?min, double?max, double?step)
        {
            if (min == null || max == null)
            {
                DoubleRange range;
                if (GetRange(function, out range))
                {
                    min = range.Min;
                    max = range.Max;
                }
                else
                {
                    min = 0;
                    max = 1;
                }
            }

            if (step == null)
            {
                step = (max - min) / 1000;
            }

            double[] input  = Matrix.Interval(min.Value, max.Value, step.Value);
            double[] output = Matrix.Apply(input, function);

            Scatterplot scatterplot = new Scatterplot(title ?? "Scatter plot");

            scatterplot.Compute(input, output);

            return(show(scatterplot));
        }
        private static ScatterplotBox show(Scatterplot scatterplot)
        {
            ScatterplotBox form       = null;
            Thread         formThread = null;

            AutoResetEvent stopWaitHandle = new AutoResetEvent(false);

            formThread = new Thread(() =>
            {
                Accord.Controls.Tools.ConfigureWindowsFormsApplication();

                // Show control in a form
                form            = new ScatterplotBox();
                form.Text       = scatterplot.Title;
                form.formThread = formThread;
                form.scatterplotView1.Scatterplot = scatterplot;

                stopWaitHandle.Set();

                Application.Run(form);
            });

            formThread.SetApartmentState(ApartmentState.STA);

            formThread.Start();

            stopWaitHandle.WaitOne();

            return(form);
        }
        /// <summary>
        ///   Constructs a new instance of the ScatterplotView.
        /// </summary>
        ///
        public DataChartView(Scatterplot scatterplot)
        {
            InitializeComponent();

            series           = new CurveList();
            seriesDataMember = new Collection <DataChartViewSeries>();

            zedGraphControl.BorderStyle = System.Windows.Forms.BorderStyle.None;
            zedGraphControl.GraphPane.Border.IsVisible = false;
            zedGraphControl.GraphPane.Border.Color     = Color.White;
            zedGraphControl.GraphPane.Border.Width     = 0;

            // zedGraphControl.IsAntiAlias = true;
            zedGraphControl.GraphPane.Fill       = new Fill(Color.White);
            zedGraphControl.GraphPane.Chart.Fill = new Fill(Color.GhostWhite);
            zedGraphControl.GraphPane.CurveList  = series;

            zedGraphControl.GraphPane.Legend.IsVisible           = true;
            zedGraphControl.GraphPane.Legend.Position            = LegendPos.Right;
            zedGraphControl.GraphPane.Legend.IsShowLegendSymbols = false;

            zedGraphControl.GraphPane.XAxis.MajorGrid.IsVisible  = true;
            zedGraphControl.GraphPane.XAxis.MinorGrid.IsVisible  = false;
            zedGraphControl.GraphPane.XAxis.MajorGrid.Color      = Color.LightGray;
            zedGraphControl.GraphPane.XAxis.MajorGrid.IsZeroLine = false;
            zedGraphControl.GraphPane.XAxis.Scale.MaxGrace       = 0;
            zedGraphControl.GraphPane.XAxis.Scale.MinGrace       = 0;

            zedGraphControl.GraphPane.YAxis.MinorGrid.IsVisible  = false;
            zedGraphControl.GraphPane.YAxis.MajorGrid.IsVisible  = true;
            zedGraphControl.GraphPane.YAxis.MajorGrid.Color      = Color.LightGray;
            zedGraphControl.GraphPane.YAxis.MajorGrid.IsZeroLine = false;
            zedGraphControl.GraphPane.YAxis.Scale.MaxGrace       = 0;
            zedGraphControl.GraphPane.YAxis.Scale.MinGrace       = 0;
        }
        public ScatterPlotForm(Scatterplot p)
        {
            InitializeComponent();

            this.plot = p;
            scatterplotView1.Scatterplot = this.plot;
        }
Exemple #8
0
        /// <summary>
        /// The main application entry point.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        public static void Main(string[] args)
        {
            // get data
            Console.WriteLine("Loading data....");
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..");

            path = Path.Combine(path, "..");
            path = Path.Combine(path, "california_housing.csv");
            var housing = Frame.ReadCsv(path, separators: ",");
            // housing = housing.Where(kv => ((decimal)kv.Value["median_house_value"]) < 500000);

            // set up a few series
            var total_rooms        = housing["total_rooms"];
            var median_house_value = housing["median_house_value"];
            var median_income      = housing["median_income"];

            // convert the house value range to thousands
            median_house_value /= 1000;

            // set up feature and label
            var feature = total_rooms.Values.ToArray();
            // var feature = median_income.Values.ToArray();
            var labels = median_house_value.Values.ToArray();

            // train the model
            Console.WriteLine("Training model....");
            var learner = new OrdinaryLeastSquares();
            var model   = learner.Learn(feature, labels);

            // show results
            Console.WriteLine($"Slope:       {model.Slope}");
            Console.WriteLine($"Intercept:   {model.Intercept}");

            // validate the model
            var predictions = model.Transform(feature);
            var rmse        = Math.Sqrt(new SquareLoss(labels).Loss(predictions));

            var range = Math.Abs(labels.Max() - labels.Min());

            Console.WriteLine($"Label range: {range}");
            Console.WriteLine($"RMSE:        {rmse} {rmse / range * 100:0.00}%");

            // generate plot arrays
            var x = feature.Concat(feature).ToArray();
            var y = predictions.Concat(labels).ToArray();

            // set up color array
            var colors1 = Enumerable.Repeat(1, labels.Length).ToArray();
            var colors2 = Enumerable.Repeat(2, labels.Length).ToArray();
            var c       = colors1.Concat(colors2).ToArray();

            // plot the data
            var plot = new Scatterplot("Training", "feature", "label");

            plot.Compute(x, y, c);
            ScatterplotBox.Show(plot);

            Console.ReadLine();
        }
        /// <summary>
        ///   Displays a scatter plot with the specified data.
        /// </summary>
        ///
        /// <param name="title">The title for the plot window.</param>
        /// <param name="x">A two column matrix containing the (x,y) data pairs as rows.</param>
        ///
        public static ScatterplotBox Show(string title, double[,] x)
        {
            Scatterplot scatterplot = new Scatterplot(title);

            scatterplot.Compute(x);

            return(show(scatterplot));
        }
        /// <summary>
        ///   Displays a scatter plot with the specified data.
        /// </summary>
        ///
        /// <param name="title">The title for the plot window.</param>
        /// <param name="x">A two column matrix containing the (x,y) data pairs as rows.</param>
        /// <param name="z">The corresponding labels for the (x,y) pairs.</param>
        ///
        public static ScatterplotBox Show(string title, double[][] x, int[] z)
        {
            Scatterplot scatterplot = new Scatterplot(title);

            scatterplot.Compute(x, z);

            return(show(scatterplot));
        }
Exemple #11
0
        /// <summary>
        ///   Displays a scatter plot with the specified data.
        /// </summary>
        ///
        /// <param name="title">The title for the plot window.</param>
        /// <param name="x">A two column matrix containing the (x,y) data pairs as rows.</param>
        /// <param name="z">The corresponding labels for the (x,y) pairs.</param>
        /// <param name="nonBlocking">If set to <c>true</c>, the caller will continue
        /// executing while the form is shown on screen. If set to <c>false</c>,
        /// the caller will be blocked until the user closes the form. Default
        /// is <c>false</c>.</param>
        ///
        public static ScatterplotBox Show(string title, double[][] x, int[] z = null, bool nonBlocking = false)
        {
            Scatterplot scatterplot = new Scatterplot(title);

            scatterplot.Compute(x, z);

            return(show(scatterplot, nonBlocking));
        }
Exemple #12
0
        private void cmdBenchmark_Click(object sender, EventArgs e)
        {
            UpdateStatus("EVALUATING", DisplayPart.Status);
            Task.Run(() =>
            {
                EvaluationResult result = _analyzer.Evaluate();
                _scatterplot            = result.Roc.GetScatterplot(true);

                UpdateStatus(result.GetDescription(), DisplayPart.Statistics);
                UpdateStatus("EVALUATED", DisplayPart.Status);
            });
        }
Exemple #13
0
    /// <summary>
    /// Initializes the DataPoint.
    /// Should always be called after creating this component.
    /// </summary>
    /// <param name="index"></param>
    /// <param name="pointSize"></param>
    /// <param name="position"></param>
    public void Initialize(int index, float pointSize, Vector3 position)
    {
        this.index         = index;
        this.pointSize     = pointSize;
        transform.position = position;

        scatterplot = transform.parent.GetComponent <Scatterplot>();
        attributes  = transform.Find("Attributes").gameObject;

        initTextMeshes();
        ShowText(false);
    }
        /// <summary>
        /// Plot the given scatterplot on screen.
        /// </summary>
        /// <param name="plot">The scatterplot to plot</param>
        private static void Plot(Scatterplot plot)
        {
            var box      = ScatterplotBox.Show(plot);
            var callback = new Action(() =>
            {
                box.SetLinesVisible(true);
                box.SetSymbolSize(0);
                box.SetScaleTight(true);
            });

            System.Threading.Thread.Sleep(100);
            box.Invoke(callback);
        }
        /// <summary>
        ///   Constructs a new instance of the ScatterplotView.
        /// </summary>
        public ScatterplotView()
        {
            InitializeComponent();

            scatterplot = new Scatterplot();

            classes = new CurveList();

            zedGraphControl.GraphPane.Title.Text       = "Scatter Plot";
            zedGraphControl.GraphPane.XAxis.Title.Text = "X";
            zedGraphControl.GraphPane.YAxis.Title.Text = "Y";
            zedGraphControl.GraphPane.Fill             = new Fill(Color.WhiteSmoke);
            zedGraphControl.GraphPane.CurveList        = classes;
        }
        /// <summary>
        /// Plot the training errors.
        /// </summary>
        /// <param name="trainingErrors">The traininer errors to plot</param>
        /// <param name="title">The chart title</param>
        /// <param name="xAxisLabel">The chart x-ais label</param>
        /// <param name="yAxisLabel">The chart y-axis label</param>
        private static void Plot(
            List <double> trainingErrors,
            string title,
            string xAxisLabel,
            string yAxisLabel)
        {
            var epochs = trainingErrors.Count();
            var x      = Enumerable.Range(0, epochs).Select(v => (double)v).ToArray();
            var y      = trainingErrors.ToArray();
            var plot   = new Scatterplot(title, xAxisLabel, yAxisLabel);

            plot.Compute(x, y);
            ScatterplotBox.Show(plot);
        }
Exemple #17
0
        public void ComputeTest2()
        {
            ScatterplotView target = new ScatterplotView();

            Scatterplot histogram = new Scatterplot();

            histogram.Compute(new double[] { 200.0, 200.0, 200.0 });

            target.DataSource = null;

            target.DataSource = histogram;

            target.DataSource = null;

            // ScatterplotBox.Show(histogram);
        }
Exemple #18
0
        /// <summary>
        /// Plot a histogram.
        /// </summary>
        /// <param name="histogram">The histogram to plot</param>
        /// <param name="title">The plot title</param>
        /// <param name="xAxisLabel">The x-axis label</param>
        /// <param name="yAxisLabel">The y-axis label</param>
        private static void Plot(Histogram histogram, string title, string xAxisLabel, string yAxisLabel)
        {
            var x = new List <double>();
            var y = new List <double>();

            for (int i = 0; i < histogram.Values.Length; i++)
            {
                var xcor = histogram.Bins[i].Range.Min;
                x.AddRange(from n in Enumerable.Range(0, histogram.Values[i]) select xcor);
                y.AddRange(from n in Enumerable.Range(0, histogram.Values[i]) select n * 1.0);
            }
            var plot = new Scatterplot(title, xAxisLabel, yAxisLabel);

            plot.Compute(x.ToArray(), y.ToArray());
            ScatterplotBox.Show(plot);
        }
Exemple #19
0
        private void featuresListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isDataLoaded)
            {
                Utilities.InfoMessageBox("Please load data or wait until data is loaded first.");
                return;
            }

            var selectedFeature = featuresListBox.SelectedItem as string;
            var featureIndex    = dataSet.dataFull.Columns.IndexOf(selectedFeature);

            Scatterplot plot = new Scatterplot(selectedFeature);

            plot.Compute(dataSet.X_Test.GetColumn(featureIndex), dataSet.Y_Test.Select(x => (double)x).ToArray <double>());
            scatterplotView.Scatterplot = plot;
        }
        /// <summary>
        /// Plot a graph on screen.
        /// </summary>
        /// <param name="xSeries">The x-series to plot</param>
        /// <param name="ySeries">The y-series to plot</param>
        /// <param name="title">The plot title</param>
        /// <param name="xAxisLabel">The x-axis label</param>
        /// <param name="yAxisLabel">The y-axis label</param>
        public static void Plot(
            Series <int, double> xSeries,
            Series <int, double> ySeries,
            string title,
            string xAxisLabel,
            string yAxisLabel)
        {
            // generate plot arrays
            var x = xSeries.Values.ToArray();
            var y = ySeries.Values.ToArray();

            // plot the graph
            var plot = new Scatterplot(title, xAxisLabel, yAxisLabel);

            plot.Compute(x, y);
            ScatterplotBox.Show(plot);
        }
Exemple #21
0
        private void PrintRandomDigit(Frame <int, string> training)
        {
            Console.WriteLine(@"Вывод случайного тренировочного образца...");
            Random rnd         = new Random();
            int    row         = rnd.Next(1, training.RowCount);
            string randomDigit = training.Rows[row]["Column1"].ToString();

            double[] x = Enumerable.Range(0, 784).Select(v => (double)(v % 28)).ToArray();
            double[] y = Enumerable.Range(0, 784).Select(v => (double)(-v / 28)).ToArray();
            int[]    z = Enumerable.Range(2, 784)
                         .Select(i => new { i, v = training.Rows[row][$"Column{i}"] as double? })
                         .Select(t => t.v > 0.5 ? 1 : 0).ToArray();

            Scatterplot plot = new Scatterplot($"Цифра {randomDigit}", "x", "y");

            plot.Compute(x, y, z);
            ScatterplotBox.Show(plot);
        }
Exemple #22
0
        public void PlotTrainingCurve(IEnumerable <double> errors, int epochCount)
        {
            double[] x = Enumerable
                         .Range(1, epochCount)
                         .Select(v => (double)v)
                         .ToArray();

            double[] y = errors.ToArray();

            Scatterplot plot = new Scatterplot(
                TrainingPlotResources.Title,
                TrainingPlotResources.YAxisTitle,
                TrainingPlotResources.XAxisTitle);

            plot.Compute(x, y);

            ScatterplotBox.Show(plot);
        }
Exemple #23
0
        public void PlotValidationCurve(IEnumerable <double> errors, int epochCount)
        {
            double[] x = Enumerable
                         .Range(1, epochCount)
                         .Select(v => (double)v)
                         .ToArray();

            double[] y = errors.ToArray();

            Scatterplot plot = new Scatterplot(
                "График изменения квадратичной ошибки тестирования",
                TrainingPlotResources.YAxisTitle,
                "Ошибки тестирования");

            plot.Compute(x, y);

            ScatterplotBox.Show(plot);
        }
    /// <summary>
    /// Creates the Scatterplots in a subroutine, one per frame.
    /// This was done to keep the programm from freezen when creating
    /// the Scatterplots.
    /// </summary>
    /// <param name="scatterplotPrefab"></param>
    /// <param name="dataSource"></param>
    /// <param name="dimCombinations"></param>
    /// <param name="matrixWidth"></param>
    /// <returns></returns>
    IEnumerator CreateScatterplotsCoroutine(GameObject scatterplotPrefab, CSVDataSource dataSource, int[,] dimCombinations, int matrixWidth)
    {
        for (int i = 0; dimCombinations.GetLength(0) > i; ++i)
        {
            int matrixPosX = i % matrixWidth * 2;
            int matrixPosZ = i / matrixWidth * 2;
            int xDim       = dimCombinations[i, 0];
            int yDim       = dimCombinations[i, 1];
            int zDim       = dimCombinations[i, 2];

            Scatterplot scatterplot = Instantiate(scatterplotPrefab, transform).GetComponent <Scatterplot>();
            scatterplot.Initialize(dataSource, matrixPosX, matrixPosZ, pointSize, xDim, yDim, zDim);
            scatterplots[i] = scatterplot;

            scatterplot.transform.localScale += Vector3.one;

            yield return(null);
        }
    }
        /// <summary>
        ///   Constructs a new instance of the ScatterplotView.
        /// </summary>
        /// 
        public ScatterplotView(Scatterplot scatterplot)
        {
            InitializeComponent();

            classes = new CurveList();

            zedGraphControl.BorderStyle = System.Windows.Forms.BorderStyle.None;
            zedGraphControl.GraphPane.Border.IsVisible = false;
            zedGraphControl.GraphPane.Border.Color = Color.White;
            zedGraphControl.GraphPane.Border.Width = 0;

            // zedGraphControl.IsAntiAlias = true;
            zedGraphControl.GraphPane.Fill = new Fill(Color.White);
            zedGraphControl.GraphPane.Chart.Fill = new Fill(Color.GhostWhite);
            zedGraphControl.GraphPane.CurveList = classes;

            zedGraphControl.GraphPane.Legend.IsVisible = true;
            zedGraphControl.GraphPane.Legend.Position = LegendPos.Right;
            zedGraphControl.GraphPane.Legend.IsShowLegendSymbols = false;

            zedGraphControl.GraphPane.XAxis.MajorGrid.IsVisible = true;
            zedGraphControl.GraphPane.XAxis.MinorGrid.IsVisible = false;
            zedGraphControl.GraphPane.XAxis.MajorGrid.Color = Color.LightGray;
            zedGraphControl.GraphPane.XAxis.MajorGrid.IsZeroLine = false;
            zedGraphControl.GraphPane.XAxis.Scale.MaxGrace = 0;
            zedGraphControl.GraphPane.XAxis.Scale.MinGrace = 0;

            zedGraphControl.GraphPane.YAxis.MinorGrid.IsVisible = false;
            zedGraphControl.GraphPane.YAxis.MajorGrid.IsVisible = true;
            zedGraphControl.GraphPane.YAxis.MajorGrid.Color = Color.LightGray;
            zedGraphControl.GraphPane.YAxis.MajorGrid.IsZeroLine = false;
            zedGraphControl.GraphPane.YAxis.Scale.MaxGrace = 0;
            zedGraphControl.GraphPane.YAxis.Scale.MinGrace = 0;

            ScaleTight = false;
            SymbolSize = 7;
            LinesVisible = false;

            this.scatterplot = scatterplot;
        }
Exemple #26
0
        /// <summary>
        ///   Generates a <see cref="Scatterplot"/> representing the ROC curve.
        /// </summary>
        ///
        /// <param name="includeRandom">
        ///   True to include a plot of the random curve (a diagonal line
        ///   going from lower left to upper right); false otherwise.</param>
        ///
        public Scatterplot GetScatterplot(bool includeRandom = false)
        {
            Scatterplot plot = new Scatterplot("Area under the ROC curve");

            plot.XAxisTitle = "1 - Specificity";
            plot.YAxisTitle = "Sensitivity";

            double[] x = Points.GetOneMinusSpecificity();
            double[] y = Points.GetSensitivity();

            if (includeRandom)
            {
                int      points = x.Length;
                double[] newx   = new double[points + 2];
                double[] newy   = new double[points + 2];
                int[]    labels = new int[points + 2];

                Array.Copy(x, newx, x.Length);
                Array.Copy(y, newy, y.Length);

                newx[points + 0]   = 0;
                newy[points + 0]   = 0;
                labels[points + 0] = 1;

                newx[points + 1]   = 1;
                newy[points + 1]   = 1;
                labels[points + 1] = 1;

                plot.Compute(newx, newy, labels);
                plot.Classes[0].Text = "Curve";
                plot.Classes[1].Text = "Random";
            }
            else
            {
                plot.Compute(x, y);
            }

            return(plot);
        }
Exemple #27
0
        /// <summary>
        /// Plot a graph on screen.
        /// </summary>
        /// <param name="feature">The features to plot</param>
        /// <param name="labels">The labels to plot</param>
        /// <param name="predictions">The predictions to plot</param>
        /// <param name="title">The plot title</param>
        /// <param name="xAxisLabel">The x-axis label</param>
        /// <param name="yAxisLabel">The y-axis label</param>
        public static void Plot(
            double[] feature,
            double[] labels,
            double[] predictions,
            string title,
            string xAxisLabel,
            string yAxisLabel)
        {
            // generate plot arrays
            var x = feature.Concat(feature).ToArray();
            var y = predictions.Concat(labels).ToArray();

            // set up color arrays
            var colors1 = Enumerable.Repeat(1, labels.Length).ToArray();
            var colors2 = Enumerable.Repeat(2, labels.Length).ToArray();
            var c       = colors1.Concat(colors2).ToArray();

            // plot the graph
            var plot = new Scatterplot(title, xAxisLabel, yAxisLabel);

            plot.Compute(x, y, c);
            ScatterplotBox.Show(plot);
        }
Exemple #28
0
        /// <summary>
        /// The main application entry point.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        public static void Main(string[] args)
        {
            // get data
            Console.WriteLine("Loading data....");
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..");

            path = Path.Combine(path, "..");
            path = Path.Combine(path, "california_housing.csv");
            var housing = Frame.ReadCsv(path, separators: ",");

            housing = housing.Where(kv => ((decimal)kv.Value["median_house_value"]) < 500000);

            // convert the house value range to thousands
            housing["median_house_value"] /= 1000;

            // shuffle row indices
            var rnd     = new Random();
            var indices = Enumerable.Range(0, housing.Rows.KeyCount).OrderBy(v => rnd.NextDouble());

            // shuffle the frame using the indices
            housing = housing.IndexRowsWith(indices).SortByRowKey();

            // create the rooms_per_person feature
            //housing.AddColumn("rooms_per_person", housing["total_rooms"] / housing["population"]);
            housing.AddColumn("rooms_per_person",
                              (housing["total_rooms"] / housing["population"]).Select(v => v.Value <= 4.0 ? v.Value : 4.0));

            // calculate the correlation matrix
            var correlation = Measures.Correlation(housing.ToArray2D <double>());

            // show the correlation matrix
            Console.WriteLine(housing.ColumnKeys.ToArray().ToString <string>());
            Console.WriteLine(correlation.ToString <double>("0.0"));

            // calculate binned latitudes
            var bins            = from b in Enumerable.Range(32, 10) select(Min: b, Max: b + 1);
            var binned_latitude =
                from l in housing["latitude"].Values
                let bin = (from b in bins where l >= b.Min && l < b.Max select b)
                          select bin.First().Min;

            // add one-hot encoding columns
            foreach (var i in Enumerable.Range(32, 10))
            {
                housing.AddColumn($"latitude {i}-{i + 1}",
                                  from l in binned_latitude
                                  select l == i ? 1 : 0);
            }

            // drop the latitude column
            housing.DropColumn("latitude");

            // show the data frame on the console
            housing.Print();

            // calculate rooms_per_person histogram
            var histogram = new Histogram();

            histogram.Compute(housing["rooms_per_person"].Values.ToArray(), 0.1); // use 1.0 without clipping

            // draw the histogram
            var x = new List <double>();
            var y = new List <double>();

            for (int i = 0; i < histogram.Values.Length; i++)
            {
                var xcor = histogram.Bins[i].Range.Min;
                x.AddRange(from n in Enumerable.Range(0, histogram.Values[i]) select xcor);
                y.AddRange(from n in Enumerable.Range(0, histogram.Values[i]) select n * 1.0);
            }
            var plot = new Scatterplot("", "rooms per person", "count");

            plot.Compute(x.ToArray(), y.ToArray());
            ScatterplotBox.Show(plot);

            Console.ReadLine();
        }
Exemple #29
0
 /// <summary>
 ///   Displays a scatter plot.
 /// </summary>
 ///
 /// <param name="scatterplot">The scatter plot to show.</param>
 /// <param name="nonBlocking">If set to <c>true</c>, the caller will continue
 /// executing while the form is shown on screen. If set to <c>false</c>,
 /// the caller will be blocked until the user closes the form. Default
 /// is <c>false</c>.</param>
 ///
 public static ScatterplotBox Show(Scatterplot scatterplot, bool nonBlocking = false)
 {
     return(show(scatterplot, nonBlocking));
 }
        private void OnDataBind()
        {
            if (dataSource == null)
                return;

            if (scatterplot == null)
                scatterplot = new Scatterplot();

            double[] x = null;
            double[] y = null;
            int[] z = null;

            if (dataSource is DataTable)
            {
                DataTable table = dataSource as DataTable;

                if (String.IsNullOrEmpty(xAxisDataMember) &&
                    table.Columns.Contains(xAxisDataMember))
                    x = table.Columns[xAxisDataMember].ToArray();

                if (String.IsNullOrEmpty(yAxisDataMember) &&
                    table.Columns.Contains(yAxisDataMember))
                    y = table.Columns[yAxisDataMember].ToArray();

                if (String.IsNullOrEmpty(labelDataMember) &&
                    table.Columns.Contains(labelDataMember))
                    z = table.Columns[labelDataMember].ToArray().ToInt32();
            }
            else if (dataSource is double[][])
            {
                double[][] source = dataSource as double[][];

                if (source.Length > 0)
                {
                    if (source[0].Length > 0)
                        x = source.GetColumn(0);

                    if (source[0].Length > 1)
                        y = source.GetColumn(1);

                    if (source[0].Length > 2)
                        z = source.GetColumn(2).ToInt32();
                }
            }
            else if (dataSource is double[,])
            {
                double[,] source = dataSource as double[,];

                if (source.Length > 0)
                {
                    int cols = source.GetLength(1);

                    if (cols > 0)
                        x = source.GetColumn(0);

                    if (cols > 1)
                        y = source.GetColumn(1);

                    if (cols > 2)
                        z = source.GetColumn(2).ToInt32();
                }
            }
            else
            {
                return; // invalid data source
            }

            if (x != null && y == null)
                y = new double[x.Length];

            else if (y != null && x == null)
                x = new double[y.Length];

            this.scatterplot.Compute(x, y, z);

            this.UpdateGraph();
        }