簡體   English   中英

如何在 MathNet.Numerics 中使用 Gamma 分布

[英]How to use a Gamma distribution in MathNet.Numerics

我想要一條分布密度曲線,它從零急劇上升到峰值,然后下降得很淺。 StatDist ,一個可以在線繪制統計分布的網站,我通過 Gamma 分布實現了這一點,例如,通過為形狀指定 2(網站上的 k)和反向比例/比率(網站上的 theta)指定 2 . 反比例(theta)越大,峰值后的下降斜率越淺。

我可以通過 MathNet.Numerics 中的 Gamma 分布實現同樣的效果嗎? 如果是這樣,怎么做? 我嘗試了幾種不同的方法。 但我發現峰值之后的值總是急劇下降到接近零。 在以下示例中,改變逆比例只會使整個曲線更平滑或更鋸齒,其中我指定了固定數量的樣本

要明白我的意思,運行代碼,改變反比例。 然后將生成的 CSV 文件加載到電子表格中,並將數據表示為折線圖。

using System.Collections.Generic;
using System.IO;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Statistics;

// [...]

// Put the path of the folder in which the CSV file is to be saved here    
const string chartFolderPath = @"C:\Insert\folder\path\here";
const double shape = 2;
const double inverseScale = 2;
const int sampleCount = 10000;
const int bucketCount = 100;
var gamma = new Gamma(shape, inverseScale);
double[] samples = new double[sampleCount];
gamma.Samples(samples);
var histogram = new Histogram(samples, bucketCount); 
var dictionary = new Dictionary<int, double>();
for (int i = 0; i < bucketCount; i++) {
  dictionary.Add(i, histogram[i].Count);
}
string csvPath = Path.Combine(
  chartFolderPath, 
  $"Gamma Densities, Shape {shape}, Inverse Scale {inverseScale}, " + 
  $"Samples {sampleCount}, Buckets {bucketCount}.csv");
using var writer = new StreamWriter(csvPath);
foreach ((int key, double value) in dictionary) {
  writer.WriteLine($"{key},{value}");
}

我缺少的是我需要選擇一個 x 軸的密度范圍,其中反比例為折線圖中的曲線提供我想要的形狀。 在形狀 2,反比例尺 2 示例中, StatDist中密度圖的 x 軸范圍建議我嘗試 0 到 16。由於我不明白的原因,我實際上不得不使用 0 到 3 來獲得一個Excel 中的曲線在視覺上與 StatDist 圖表中的大致相同。 以下代碼顯示了我是如何做到的。

using System.Collections.Generic;
using System.IO;
using MathNet.Numerics.Distributions;

// ...

// Put the path of the folder in which the CSV file is to be saved here    
const string chartFolderPath = @"C:\Insert\folder\path\here";
const double shape = 2;
const double inverseScale = 2;
const double xMin = 0;
const double xMax = 3;
var gamma = new Gamma(shape, inverseScale);
var densities = new Dictionary<double, double>();
for (double x = xMin; x <= xMax; x += 0.1) {
  densities.Add(x, gamma.Density(x));
}
string csvPath = Path.Combine(
  chartFolderPath, 
  $"Gamma Densities, Shape {shape}, Inverse Scale {inverseScale}, " + 
  $"Range {xMin} to {xMax}.csv");
using var writer = new StreamWriter(csvPath);
foreach ((double key, double value) in densities) {
  writer.WriteLine($"{key},{value}");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM