我有一个IEnumerable<double>
数据样本。我想计算信号/数据的90%置信区间。我有MathNET library可供我使用,但我对如何正确使用库感到困惑。根据我的数据,我们的想法是返回两个包含原始信号置信区间的附加数据数组
using MathNet.Numerics.Statistics;
using MathNet.Numerics.Distributions;
public static List<double[]> ConfidenceIntervals(IEnumerable<double> sample, double interval)
{
Contract.Requires(interval > 0 && interval < 1.0);
int sampleSize = sample.Count();
double alpha = 1.0 - interval;
double mean = sample.Mean();
double sd = sample.StandardDeviation();
double t, mu;
double[] upper = new double[sampleSize];
double[] lower = new double[sampleSize];
StudentT studentT = new StudentT(mean, alpha, sampleSize - 1);
int index = 0;
foreach (double d in sample)
{
t = studentT.CumulativeDistribution(d);
double tmp = t * (sd / Math.Sqrt(sampleSize));
mu = mean - tmp;
upper[index] = d + mu;
lower[index] = d - mu;
}
return new List<double[]>() { upper, lower };
}
这在数学方面确实不复杂,我对如何正确使用MathNET library中可用的函数/方法感到困惑。
答案 0 :(得分:6)
我不完全确定我理解信号的置信区间应该如何应用于信号的每个样本,但我们可以如下计算样本集的置信区间:
public static Tuple<double, double> A(double[] samples, double interval)
{
double theta = (interval + 1.0)/2;
double mean = samples.Mean();
double sd = samples.StandardDeviation();
double T = StudentT.InvCDF(0,1,samples.Length-1,theta);
double t = T * (sd / Math.Sqrt(samples.Length));
return Tuple.Create(mean-t, mean+t);
}
除了我们计算T的行不能编译,因为遗憾的是当前Math.NET Numerics中还没有StudentT.InvCDF
。但我们仍然可以在此期间以数字方式对其进行评估:
var student = new StudentT(0,1,samples.Length-1);
double T = FindRoots.OfFunction(x => student.CumulativeDistribution(x)-theta,-800,800);
例如,对于16个样本和alpha 0.05,我们按预期得到2.131。如果有超过60-100个样本,也可以用正态分布近似:
double T = Nomal.InvCDF(0,1,theta);
总而言之:
public static Tuple<double, double> B(double[] samples, double interval)
{
double theta = (interval + 1.0)/2;
double T = FindRoots.OfFunction(x => StudentT.CDF(0,1,samples.Length-1,x)-theta,-800,800);
double mean = samples.Mean();
double sd = samples.StandardDeviation();
double t = T * (sd / Math.Sqrt(samples.Length));
return Tuple.Create(mean-t, mean+t);
}
这还不是完整的答案,因为我知道你想以某种方式将置信区间应用于每个样本,但希望它有助于实现目标。
PS:使用Math.NET Numerics v3.0.0-alpha7
答案 1 :(得分:1)
我注意到你没有在foreach
循环中增加索引值。这将使索引0处的值替换为下一个计算(当您尝试设置upper[index]
和lower[index]
值时)。
所以我想这就是你得到错误结果的原因。
如果是这样,您的代码应为
using MathNet.Numerics.Statistics;
using MathNet.Numerics.Distributions;
public static List<double[]> ConfidenceIntervals(IEnumerable<double> sample, double interval)
{
Contract.Requires(interval > 0 && interval < 1.0);
int sampleSize = sample.Count();
double alpha = 1.0 - interval;
double mean = sample.Mean();
double sd = sample.StandardDeviation();
double t, mu;
double[] upper = new double[sampleSize];
double[] lower = new double[sampleSize];
StudentT studentT = new StudentT(mean, alpha, sampleSize - 1);
int index = 0;
foreach (double d in sample)
{
t = studentT.CumulativeDistribution(d);
double tmp = t * (sd / Math.Sqrt(sampleSize));
mu = mean - tmp;
upper[index] = d + mu;
lower[index] = d - mu;
index++;
}
return new List<double[]>() { upper, lower };
}