C# Multiple Linear Regression Example

← All NMath Stats Code Examples

```using System;
using System.IO;

using CenterSpace.NMath.Core;
using CenterSpace.NMath.Stats;

namespace CenterSpace.NMath.Stats.Examples.CSharp
{
/// <summary>
/// A .NET example in C# showing how to perform multiple linear regression.
/// </summary>
class MultipleLinearRegressionExample
{

static void Main( string[] args )
{
var dataStream = new StreamReader( "MultipleLinearRegressionExample.dat" );

// First read in the independent (or predictor) values. This is a matrix
// with one column and a row for each amounts measurement.
var longLatValues = new DoubleMatrix( dataStream );

// Next, read in the responses. These are the readings of the gas
// chromatograph
var janTemp = new DoubleVector( dataStream );

// Print out the amounts and responses values.
Console.WriteLine();
Console.WriteLine( "Longitudes and latitudes =" );
Console.WriteLine( longLatValues.ToTabDelimited( "G7" ) );
Console.WriteLine();
Console.WriteLine( "January temperatures =" );
Console.WriteLine( janTemp );
Console.WriteLine();

var regression = new LinearRegression( longLatValues, janTemp, true );
var regressionAnova = new LinearRegressionAnova( regression );

var regressionStats = new DataFrame();
regressionStats.AddColumn( new DFNumericColumn( "Sum of Squares" ) );
var dfCol = new DFIntColumn( "df" );
regressionStats.AddColumn( new DFNumericColumn( "Mean Square" ) );
regressionStats.AddColumn( new DFNumericColumn( "F-ratio" ) );

regressionAnova.ModelDegreesOfFreedom,
regressionAnova.MeanSquaredRegression,
regressionAnova.FStatistic );

regressionAnova.ErrorDegreesOfFreedom,
regressionAnova.MeanSquaredResidual,
Double.NaN );

Console.WriteLine( "Dependent Variable is:       January Temp" );
Console.WriteLine();
Console.WriteLine( "{0} total cases", regression.NumberOfObservations );
Console.WriteLine();
Console.WriteLine( "R squared = " + regressionAnova.RSquared.ToString( "P" ) );
Console.WriteLine( "s = {0} with {1} degrees of freedom",
System.Math.Sqrt( regression.Variance ).ToString( "G5" ),
regression.NumberOfObservations - regression.NumberOfParameters );
Console.WriteLine();
Console.WriteLine( regressionStats );

Console.WriteLine();
Console.WriteLine( "Press Enter Key" );