本文整理汇总了C#中Beta类的典型用法代码示例。如果您正苦于以下问题:C# Beta类的具体用法?C# Beta怎么用?C# Beta使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Beta类属于命名空间,在下文中一共展示了Beta类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main()
{
Alpha objA = new Alpha(4);
Beta objВ = new Beta (9);
// Продемонстрировать сначала контравариантность.
// Объявить делегат SomeOp<Alpha> и задать для него метод IsEven.
SomeOp<Alpha> checklt = IsEven;
// Объявить делегат SomeOp<Beta>.
SomeOp<Beta> checklt2;
//А теперь- присвоить делегат SomeOp<Alpha> делегату SomeOp<Beta>.
// *** Это допустимо только благодаря контравариантности. ***
checklt2 = checklt;
// Вызвать метод через делегат.
Console.WriteLine(checklt2(objВ));
// Далее, продемонстрировать контравариантность.
// Объявить сначала два делегата типа AnotherOp.
// Здесь возвращаемым типом является класс Beta,
//а параметром типа — класс Alpha.
// Обратите внимание на то, что для делегата modifylt
// задается метод Changelt.
AnotherOp<Beta, Alpha> modifylt = Changelt;
// Здесь возвращаемым типом является класс Alpha,
//а параметром типа — тот же класс Alpha.
AnotherOp<Alpha, Alpha> modifyIt2;
// А теперь присвоить делегат modifylt делегату modifyIt2.
// *** Это допустимо только благодаря ковариантности. ***
modifyIt2 = modifylt;
// Вызвать метод и вывести результаты на экран.
objA = modifyIt2(objA);
Console.WriteLine(objA.Val);
}
示例2: Main
static void Main(){
Stopwatch timer = new Stopwatch();
timer.Start();
Alpha oAlpha = new Alpha();
Beta oBeta = new Beta();
// create the threads
Thread aThread = new Thread(new ThreadStart(oAlpha.Counter));
Thread bThread = new Thread(new ThreadStart(oBeta.Counter));
// start the threads
aThread.Start();
bThread.Start();
// spin until both threads have finished
while(aThread.IsAlive && bThread.IsAlive);
timer.Stop();
TimeSpan ts = timer.Elapsed;
Console.WriteLine("Execution Time: " + ts);
}
示例3: Run
// Sample data from a DINA/NIDA model and then use Infer.NET to recover the parameters.
public void Run()
{
InferenceEngine engine = new InferenceEngine();
if (!(engine.Algorithm is ExpectationPropagation))
{
Console.WriteLine("This example only runs with Expectation Propagation");
return;
}
bool useDina = true;
Beta slipPrior = new Beta(1, 10);
Beta guessPrior = new Beta(1, 10);
Rand.Restart(0);
int nStudents = 100;
int nQuestions = 20;
int nSkills = 3;
int[][] skillsRequired = new int[nQuestions][];
for (int q = 0; q < nQuestions; q++) {
// each question requires a random set of skills
int[] skills = Rand.Perm(nSkills);
int n = Rand.Int(nSkills)+1;
skillsRequired[q] = Util.ArrayInit(n, i => skills[i]);
Console.WriteLine("skillsRequired[{0}] = {1}", q, Util.CollectionToString(skillsRequired[q]));
}
double[] pSkill, slip, guess;
bool[][] hasSkill;
VariableArray<double> slipVar, guessVar, pSkillVar;
VariableArray<VariableArray<bool>,bool[][]> hasSkillVar;
if (useDina) {
bool[][] responses = DinaSample(nStudents, nSkills, skillsRequired, slipPrior, guessPrior, out pSkill, out slip, out guess, out hasSkill);
DinaModel(responses, nSkills, skillsRequired, slipPrior, guessPrior, out pSkillVar, out slipVar, out guessVar, out hasSkillVar);
} else {
bool[][] responses = NidaSample(nStudents, nSkills, skillsRequired, slipPrior, guessPrior, out pSkill, out slip, out guess, out hasSkill);
NidaModel(responses, nSkills, skillsRequired, slipPrior, guessPrior, out pSkillVar, out slipVar, out guessVar, out hasSkillVar);
}
engine.NumberOfIterations = 10;
Bernoulli[][] hasSkillPost = engine.Infer<Bernoulli[][]>(hasSkillVar);
int numErrors = 0;
for (int i = 0; i < nStudents; i++) {
for (int s = 0; s < nSkills; s++) {
if (hasSkill[i][s] != (hasSkillPost[i][s].LogOdds > 0)) numErrors++;
}
}
Console.WriteLine("{0:0}% of skills recovered correctly", 100.0 - 100.0*numErrors/(nStudents*nSkills));
Beta[] pSkillPost = engine.Infer<Beta[]>(pSkillVar);
Beta[] slipPost = engine.Infer<Beta[]>(slipVar);
Beta[] guessPost = engine.Infer<Beta[]>(guessVar);
for (int s = 0; s < nSkills; s++) {
Console.WriteLine("pSkill[{0}] = {1} (sampled from {2})", s, pSkillPost[s], pSkill[s].ToString("g4"));
}
for (int i = 0; i < Math.Min(3,slipPost.Length); i++) {
Console.WriteLine("slip[{0}] = {1} (sampled from {2})", i, slipPost[i], slip[i].ToString("g4"));
}
for (int i = 0; i < Math.Min(3,guessPost.Length); i++) {
Console.WriteLine("guess[{0}] = {1} (sampled from {2})", i, guessPost[i], guess[i].ToString("g4"));
}
}
示例4: LogAverageFactor
/// <summary>
/// Evidence message for EP
/// </summary>
/// <param name="sample">Constant value for 'sample'.</param>
/// <param name="p">Incoming message from 'p'.</param>
/// <param name="trialCount">Incoming message from 'trialCount'.</param>
/// <returns>Logarithm of the factor's average value across the given argument distributions</returns>
/// <remarks><para>
/// The formula for the result is <c>log(sum_(p,trialCount) p(p,trialCount) factor(sample,trialCount,p))</c>.
/// </para></remarks>
public static double LogAverageFactor(int sample, Beta p, Discrete trialCount)
{
double logZ = Double.NegativeInfinity;
for (int n = 0; n < trialCount.Dimension; n++)
{
logZ = MMath.LogSumExp(logZ, trialCount.GetLogProb(n) + LogAverageFactor(sample, p, n));
}
return logZ;
}
示例5: Infer
public void Infer(bool[] treated, bool[] placebo)
{
// Set the observed values
numberPlacebo.ObservedValue = placebo.Length;
numberTreated.ObservedValue = treated.Length;
placeboGroupOutcomes.ObservedValue = placebo;
treatedGroupOutcomes.ObservedValue = treated;
// Infer the hidden values
posteriorTreatmentIsEffective = engine.Infer<Bernoulli>(isEffective);
posteriorProbIfPlacebo = engine.Infer<Beta>(probIfPlacebo);
posteriorProbIfTreated = engine.Infer<Beta>(probIfTreated);
}
示例6: drawBetaDistribution
private static void drawBetaDistribution(Rectangle rect, Beta dist)
{
GradientStopCollection gsc = new GradientStopCollection();
int numStops = 21;
double mean = dist.GetMean();
double meanDensity = Math.Exp(dist.GetLogProb(mean));
double inc = 1.0 / (numStops-1);
double curr = 0.0;
double maxLogProb = Double.MinValue;
double minLogProb = -5.0;
for (int i=0; i < numStops; i++)
{
double logProb = dist.GetLogProb(curr);
if (logProb > maxLogProb) maxLogProb = logProb;
curr += inc;
}
if (maxLogProb <= minLogProb)
maxLogProb = minLogProb + 1.0;
double diff = maxLogProb - minLogProb;
double mult = 1.0 / (maxLogProb - minLogProb);
curr = 0.0;
double blueLeft = 0; double blueRight = 0;
double redLeft = 255; double redRight = 255;
double greenLeft = 255; double greenRight = 255;
for (int i=0; i < numStops; i++)
{
double red, green, blue;
double logProb = dist.GetLogProb(curr);
if (logProb < minLogProb) logProb = minLogProb;
double level = mult * (logProb - minLogProb);
red = level * (mean * redRight + (1.0 - mean) * redLeft);
green = level * (mean * greenRight + (1.0 - mean) * greenLeft);
blue =level * (mean * blueRight + (1.0 - mean) * blueLeft);
byte redb = red < 0.0 ? (byte)0 : red > 255.0 ? (byte)255 : (byte)red;
byte greenb = green < 0.0 ? (byte)0 : green > 255.0 ? (byte)255 : (byte)green;
byte blueb = blue < 0.0 ? (byte)0 : blue > 255.0 ? (byte)255 : (byte)blue;
gsc.Add(new GradientStop { Color =new Color() { A = 255, R = redb, G = greenb, B = blueb } , Offset = curr});
curr += inc;
}
LinearGradientBrush brush = rect.Fill as LinearGradientBrush;
brush.GradientStops = gsc;
}
示例7: DinaSample
// Sample data from the DINA model
public static bool[][] DinaSample(int nStudents, int nSkills, int[][] skillsRequired, Beta slipPrior, Beta guessPrior,
out double[] pSkillOut, out double[] slip, out double[] guess, out bool[][] hasSkill)
{
int nQuestions = skillsRequired.Length;
double[] pSkill = Util.ArrayInit(nSkills, q => Rand.Double());
slip = Util.ArrayInit(nQuestions, q => slipPrior.Sample());
guess = Util.ArrayInit(nQuestions, q => guessPrior.Sample());
hasSkill = Util.ArrayInit(nStudents, t => Util.ArrayInit(nSkills, s => Rand.Double() < pSkill[s]));
bool[][] responses = new bool[nStudents][];
for (int t = 0; t < nStudents; t++) {
responses[t] = new bool[nQuestions];
for (int q = 0; q < nQuestions; q++) {
bool hasAllSkills = Factor.AllTrue(Factor.Subarray(hasSkill[t], skillsRequired[q]));
if (hasAllSkills) responses[t][q] = (Rand.Double() > slip[q]);
else responses[t][q] = (Rand.Double() < guess[q]);
}
}
pSkillOut = pSkill;
return responses;
}
示例8: ValidateMaximum
public void ValidateMaximum()
{
var n = new Beta(1.0, 1.0);
Assert.AreEqual(1.0, n.Maximum);
}
示例9: ValidateToString
public void ValidateToString()
{
var n = new Beta(1.0, 2.0);
Assert.AreEqual("Beta(A = 1, B = 2)", n.ToString());
}
示例10: LogEvidenceRatio
public static double LogEvidenceRatio(Bernoulli sample, Beta probTrue)
{
return 0.0;
}
示例11: LogAverageFactor
/// <summary>
/// Evidence message for EP
/// </summary>
/// <param name="sample">Constant value for 'sample'.</param>
/// <param name="probTrue">Incoming message from 'probTrue'.</param>
/// <returns>Logarithm of the factor's average value across the given argument distributions</returns>
/// <remarks><para>
/// The formula for the result is <c>log(sum_(probTrue) p(probTrue) factor(sample,probTrue))</c>.
/// </para></remarks>
public static double LogAverageFactor(bool sample, Beta probTrue)
{
Bernoulli to_sample = SampleAverageConditional(probTrue);
return to_sample.GetLogProb(sample);
}
示例12: LogEvidenceRatio
public static double LogEvidenceRatio(Beta sample, double mean, double variance) { return 0.0; }
示例13: MeanAverageLogarithm
/// <summary>
/// VMP message to 'mean'
/// </summary>
/// <param name="mean">Incoming message from 'mean'. Must be a proper distribution. If uniform, the result will be uniform. Must be a proper distribution. If uniform, the result will be uniform.</param>
/// <param name="totalCount">Incoming message from 'totalCount'. Must be a proper distribution. If uniform, the result will be uniform.</param>
/// <param name="prob">Incoming message from 'prob'. Must be a proper distribution. If uniform, the result will be uniform.</param>
/// <param name="to_mean">Previous outgoing message to 'Mean'.</param>
/// <returns>The outgoing VMP message to the 'mean' argument</returns>
/// <remarks><para>
/// The outgoing message is the exponential of the average log-factor value, where the average is over all arguments except 'mean'.
/// The formula is <c>exp(sum_(totalCount,prob) p(totalCount,prob) log(factor(prob,mean,totalCount)))</c>.
/// </para></remarks>
/// <exception cref="ImproperMessageException"><paramref name="mean"/> is not a proper distribution</exception>
/// <exception cref="ImproperMessageException"><paramref name="totalCount"/> is not a proper distribution</exception>
/// <exception cref="ImproperMessageException"><paramref name="prob"/> is not a proper distribution</exception>
public static Beta MeanAverageLogarithm([Proper] Beta mean, [Proper] Gamma totalCount, [SkipIfUniform] Beta prob, Beta to_mean)
{
// Calculate gradient using method for DirichletOp
double ELogP, ELogOneMinusP;
prob.GetMeanLogs(out ELogP, out ELogOneMinusP);
Vector gradS = DirichletOp.CalculateGradientForMean(
Vector.FromArray(new double[] { mean.TrueCount, mean.FalseCount }),
totalCount,
Vector.FromArray(new double[] { ELogP, ELogOneMinusP }));
// Project onto a Beta distribution
Matrix A = new Matrix(2, 2);
double c = MMath.Trigamma(mean.TotalCount);
A[0, 0] = MMath.Trigamma(mean.TrueCount) - c;
A[1, 0] = A[0, 1] = -c;
A[1, 1] = MMath.Trigamma(mean.FalseCount) - c;
Vector theta = GammaFromShapeAndRateOp.twoByTwoInverse(A)*gradS;
Beta approximateFactor = new Beta(theta[0] + 1, theta[1] + 1);
if (damping == 0.0)
return approximateFactor;
else
return (approximateFactor^(1-damping)) * (to_mean ^ damping);
}
示例14: ValidateMedianThrowsNotSupportedException
public void ValidateMedianThrowsNotSupportedException()
{
var n = new Beta(0.0, 1.0);
Assert.Throws<NotSupportedException>(() => { var m = n.Median; });
}
示例15: CanSample
public void CanSample()
{
var n = new Beta(2.0, 3.0);
n.Sample();
}