Implement Bayesian inference using PHP: Part 2, IBM developerWorks, April 13, 2004.

In this second article on Bayesian inference, Paul Meagher examines how you can use Bayes methods to solve parameter estimation problems. Relevant concepts are explained in the context of Web survey analysis using PHP and JPGraph.

Last updated: April 14, 2004 - 2:30 AM AST


Demos:

Source code listing:



<?php

/**
* Script to graph the Beta distribution for specific 
* values of a and b.
*
* Much of the plotting code below has been adapted from 
* example code written by JPGraph author Johan Persson.
*
* To get this working locally, you must install JPGraph
* and set the JPGRAPH constant to the folder where the
* JPGraph source code resides.

* @see http://www.aditus.nu/jpgraph/index.php
*/

require_once "../config.php";
  
include_once 
JPGRAPH "/src/jpgraph.php";
include_once 
JPGRAPH "/src/jpgraph_line.php";
include_once 
JPGRAPH "/src/jpgraph_scatter.php";
include_once 
JPGRAPH "/src/jpgraph_regstat.php";

require_once 
"../BetaDistribution.php"

$a 5;  // num successes
$b 20// num failures

$beta = new BetaDistribution($a$b); 

$i 0;  // counter 
for($p 0.01$p <= 0.99$p += 0.04 ) {
  
$pdf_vals[$i]   = $beta->PDF($p);
  
$parameters[$i] = $p;
  
$i++;
}

$mean  sprintf("%0.3f"$beta->getMean());
$stdev sprintf("%0.3f"$beta->getStandardDeviation());

$spline = new Spline($parameters$pdf_vals);
list(
$newx,$newy) = $spline->Get(50);

$graph = new Graph(450350);
$graph->SetMargin(60204030);

$graph->title->Set("Beta[$a,$b]");
$graph->subtitle->Set(" Mean = $mean, Stdev = $stdev ");
$graph->subtitle->SetColor('darkred');

$graph->SetMarginColor('lightblue');

$graph->SetScale('linlin');

$graph->xaxis->SetPos("min"); 

$graph->xaxis->SetLabelFormat('%1.2f');
$graph->yaxis->SetLabelFormat('%1.2f');

$graph->xaxis->SetTitle("p","center");
$graph->yaxis->SetTitleMargin(40);
$graph->yaxis->SetTitle("f(p)""center");
  
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);

$splot = new ScatterPlot($pdf_vals$parameters);
$splot->mark->SetFillColor('red@0.3');
$splot->mark->SetColor('red@0.5');

$lplot = new LinePlot($newy$newx);
$lplot->SetColor('navy');

$graph->Add($lplot);
$graph->Add($splot);
$graph->Stroke();

?>



Back to source code listing